"use client";

import { useState } from "react";
import { ArrowUpRight, Plus, Trash2 } from "lucide-react";
import type {
  AssetCondition,
  AssetEntry,
  OwnershipStatus,
  StepFarmAssetsData,
} from "@/lib/api-types";
import { t, type WizardLocale } from "@/lib/i18n/wizard-labels";
import { useReferenceOptions } from "../hooks/useReferenceOptions";

interface Props {
  data: Partial<StepFarmAssetsData>;
  loading: boolean;
  locale?: WizardLocale;
  onSave: (data: StepFarmAssetsData) => Promise<unknown>;
  onSaveDraft: (data: Partial<StepFarmAssetsData>) => Promise<unknown>;
}

interface AssetForm {
  assetType: string;
  condition: AssetCondition;
  estimatedValue: string;
  quantity: string;
}

export default function StepFarmAssets({
  data,
  loading,
  locale = "uz",
  onSave,
}: Props) {
  const { options: assetTypes, loading: optionsLoading } = useReferenceOptions("asset_types", "UZ", {
    locale,
  });
  const [assets, setAssets] = useState<AssetForm[]>(
    data?.assets?.length
      ? data.assets.map((a) => ({
          assetType: a.assetType,
          condition: a.condition,
          estimatedValue: String(a.estimatedValue ?? ""),
          quantity: String(a.quantity ?? 1),
        }))
      : [{ assetType: "", condition: "good", estimatedValue: "", quantity: "1" }],
  );
  const [ownership, setOwnership] = useState<OwnershipStatus>(data?.ownership ?? "owned");
  const [titleProof, setTitleProof] = useState(data?.titleProof ?? false);
  const [storageCapacity, setStorageCapacity] = useState(
    data?.storageCapacity != null ? String(data.storageCapacity) : "",
  );

  const addAsset = () =>
    setAssets((prev) => [
      ...prev,
      { assetType: "", condition: "good", estimatedValue: "", quantity: "1" },
    ]);

  const removeAsset = (i: number) => setAssets((prev) => prev.filter((_, idx) => idx !== i));

  const updateAsset = (i: number, field: keyof AssetForm, value: string) =>
    setAssets((prev) => prev.map((a, idx) => (idx === i ? { ...a, [field]: value } : a)));

  const isValid = assets.length > 0 && assets.every((a) => a.assetType);

  const handleSave = () => {
    const entries: AssetEntry[] = assets.map((a) => ({
      assetType: a.assetType,
      condition: a.condition,
      estimatedValue: Number(a.estimatedValue) || 0,
      quantity: Number(a.quantity) || 1,
    }));
    const totalAssetValueUsd = entries.reduce((sum, a) => sum + a.estimatedValue, 0);
    onSave({
      assets: entries,
      totalAssetValueUsd,
      ownership,
      titleProof,
      storageCapacity: storageCapacity ? Number(storageCapacity) : undefined,
    });
  };

  const inputClass =
    "w-full px-3 py-2.5 rounded-lg border border-border bg-surface font-inter text-sm text-ink placeholder:text-muted/70 focus:outline-none focus:border-green-deep/40 focus:ring-1 focus:ring-green-deep/20";
  const selectClass = `${inputClass} appearance-none cursor-pointer`;

  return (
    <div className="space-y-5">
      <div>
        <h2 className="font-onest text-2xl font-semibold text-ink">
          {locale === "ru" ? "Активы фермы" : "Ferma aktivlari"}
        </h2>
        <p className="mt-1 font-inter text-sm text-ink-soft">
          {locale === "ru"
            ? "Оборудование и скот для оценки залога."
            : "Garov baholash uchun uskunalar va qoramol."}
        </p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 rounded-xl border border-border bg-surface p-4">
        <div>
          <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
            {locale === "ru" ? "Право собственности" : "Egalik huquqi"}
          </label>
          <select
            value={ownership}
            onChange={(e) => setOwnership(e.target.value as OwnershipStatus)}
            className={selectClass}
          >
            {(["owned", "leased", "shared", "unknown"] as const).map((o) => (
              <option key={o} value={o}>
                {locale === "ru"
                  ? { owned: "В собственности", leased: "Аренда", shared: "Совместное", unknown: "Неизвестно" }[o]
                  : { owned: "Egasiga tegishli", leased: "Ijara", shared: "Umumiy", unknown: "Noma'lum" }[o]}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
            {locale === "ru" ? "Ёмкость хранения (т)" : "Saqlash sig'imi (t)"}
          </label>
          <input
            type="number"
            min="0"
            value={storageCapacity}
            onChange={(e) => setStorageCapacity(e.target.value)}
            className={inputClass}
          />
        </div>
        <label className="flex items-end gap-2 pb-2 cursor-pointer">
          <input
            type="checkbox"
            checked={titleProof}
            onChange={(e) => setTitleProof(e.target.checked)}
            className="w-4 h-4 rounded border-border text-green-deep cursor-pointer"
          />
          <span className="font-inter text-xs text-ink-soft">
            {locale === "ru" ? "Есть документ на право" : "Huquq hujjati bor"}
          </span>
        </label>
      </div>

      {assets.map((asset, i) => (
        <div key={i} className="rounded-xl border border-border bg-surface p-4 space-y-3">
          <div className="flex items-center justify-between">
            <span className="font-inter text-sm font-medium text-ink/60">
              {locale === "ru" ? "Актив" : "Aktiv"} {i + 1}
            </span>
            {assets.length > 1 && (
              <button type="button" onClick={() => removeAsset(i)} className="text-red-400 hover:text-red-600 cursor-pointer">
                <Trash2 className="w-4 h-4" />
              </button>
            )}
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {locale === "ru" ? "Тип" : "Turi"}
              </label>
              <select
                value={asset.assetType}
                onChange={(e) => updateAsset(i, "assetType", e.target.value)}
                className={selectClass}
              >
                <option value="" disabled>{t("common.select", locale)}</option>
                {assetTypes.map((opt) => (
                  <option key={opt.value} value={opt.value}>{opt.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {locale === "ru" ? "Состояние" : "Holati"}
              </label>
              <select
                value={asset.condition}
                onChange={(e) => updateAsset(i, "condition", e.target.value as AssetCondition)}
                className={selectClass}
              >
                {(["new", "good", "fair", "poor"] as const).map((c) => (
                  <option key={c} value={c}>
                    {c.charAt(0).toUpperCase() + c.slice(1)}
                  </option>
                ))}
              </select>
            </div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {locale === "ru" ? "Стоимость (USD)" : "Qiymat (USD)"}
              </label>
              <input
                type="number"
                min="0"
                value={asset.estimatedValue}
                onChange={(e) => updateAsset(i, "estimatedValue", e.target.value)}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {locale === "ru" ? "Количество" : "Soni"}
              </label>
              <input
                type="number"
                min="1"
                value={asset.quantity}
                onChange={(e) => updateAsset(i, "quantity", e.target.value)}
                className={inputClass}
              />
            </div>
          </div>
        </div>
      ))}

      <button
        type="button"
        onClick={addAsset}
        className="flex items-center gap-2 text-sm font-inter font-medium text-green-deep hover:underline cursor-pointer"
      >
        <Plus className="w-4 h-4" /> {t("common.addAnother", locale)}
      </button>

      <button
        onClick={handleSave}
        disabled={!isValid || loading || optionsLoading}
        className="w-full flex items-center justify-center gap-2 py-3.5 rounded-full bg-green-deep text-white font-inter font-medium text-base hover:bg-green-deep/90 transition-colors disabled:opacity-50 cursor-pointer"
      >
        {loading ? t("common.saving", locale) : t("common.saveContinue", locale)}
        <ArrowUpRight className="w-4 h-4" />
      </button>
    </div>
  );
}
