"use client";

import { useMemo, useState } from "react";
import { ArrowUpRight, MapPin, Plus, Trash2 } from "lucide-react";
import type {
  IrrigationSource,
  LandParcel,
  LandUseType,
  StepLandSketchData,
  TenureType,
} from "@/lib/api-types";
import { enumLabel, t, type WizardLocale } from "@/lib/i18n/wizard-labels";
import { useReferenceOptions } from "../hooks/useReferenceOptions";

interface Props {
  data: Partial<StepLandSketchData>;
  loading: boolean;
  locale?: WizardLocale;
  defaultDistrict?: string;
  defaultRegion?: string;
  onSave: (data: StepLandSketchData) => Promise<unknown>;
  onSaveDraft: (data: Partial<StepLandSketchData>) => Promise<unknown>;
}

interface ParcelForm extends Omit<LandParcel, "areaHa"> {
  areaHa: string;
  parcelId: string;
}

const emptyParcel = (district = "", isPrimary = false): ParcelForm => ({
  parcelId: `parcel-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
  district,
  village: "",
  areaHa: "",
  tenureType: "owned",
  landUseType: "irrigated_cropland",
  irrigationSource: "canal",
  isPrimary,
  registryRef: "",
});

function toParcelForm(p: LandParcel & { parcelId?: string }, index: number): ParcelForm {
  return {
    parcelId: p.parcelId ?? `parcel-${index}`,
    district: p.district,
    village: p.village,
    areaHa: String(p.areaHa ?? ""),
    tenureType: p.tenureType,
    landUseType: p.landUseType,
    irrigationSource: p.irrigationSource,
    isPrimary: p.isPrimary,
    registryRef: p.registryRef ?? "",
  };
}

export default function StepLandSketch({
  data,
  loading,
  locale = "uz",
  defaultDistrict = "",
  defaultRegion = "",
  onSave,
}: Props) {
  const { options: districts, loading: districtsLoading } = useReferenceOptions("districts", "UZ", {
    region: defaultRegion || undefined,
    locale,
  });

  const initialParcels = useMemo(() => {
    if (data?.parcels?.length) {
      return data.parcels.map((p, i) => toParcelForm(p, i));
    }
    return [emptyParcel(defaultDistrict, true)];
  }, [data?.parcels, defaultDistrict]);

  const [parcels, setParcels] = useState<ParcelForm[]>(initialParcels);

  const setPrimary = (index: number) => {
    setParcels((prev) => prev.map((p, i) => ({ ...p, isPrimary: i === index })));
  };

  const updateParcel = (index: number, field: keyof ParcelForm, value: string | boolean) => {
    setParcels((prev) =>
      prev.map((p, i) => (i === index ? { ...p, [field]: value } : p)),
    );
  };

  const addParcel = () => {
    setParcels((prev) => [...prev, emptyParcel(defaultDistrict, prev.length === 0)]);
  };

  const removeParcel = (index: number) => {
    setParcels((prev) => {
      const next = prev.filter((_, i) => i !== index);
      if (next.length > 0 && !next.some((p) => p.isPrimary)) {
        next[0] = { ...next[0], isPrimary: true };
      }
      return next;
    });
  };

  const isValid =
    parcels.length > 0 &&
    parcels.some((p) => p.isPrimary) &&
    parcels.every((p) => p.district && p.village && p.areaHa && Number(p.areaHa) > 0);

  const handleSave = () => {
    onSave({
      parcels: parcels.map(({ parcelId: _id, ...p }) => ({
        district: p.district,
        village: p.village,
        areaHa: Number(p.areaHa),
        tenureType: p.tenureType as TenureType,
        landUseType: p.landUseType as LandUseType,
        irrigationSource: p.irrigationSource as IrrigationSource,
        isPrimary: p.isPrimary,
        ...(p.registryRef ? { registryRef: p.registryRef } : {}),
      })),
    });
  };

  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">{t("landSketch.title", locale)}</h2>
        <p className="mt-1 font-inter text-sm text-ink-soft">{t("landSketch.subtitle", locale)}</p>
      </div>

      <div className="rounded-2xl border border-green-deep/15 bg-green-deep/5 p-5 flex items-start gap-3">
        <MapPin className="w-5 h-5 text-green-deep mt-0.5 shrink-0" />
        <p className="font-inter text-sm text-ink-soft leading-relaxed">
          {t("landSketch.agentNote", locale)}
        </p>
      </div>

      {parcels.map((parcel, i) => (
        <div key={parcel.parcelId} className="rounded-xl border border-border bg-surface p-4 space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="font-inter text-sm font-medium text-ink/60">
                {t("landSketch.parcel", locale)} {i + 1}
              </span>
              {parcel.isPrimary && (
                <span className="text-[10px] font-inter font-medium px-2 py-0.5 rounded-full bg-green-deep/10 text-green-deep">
                  {t("landSketch.primaryParcel", locale)}
                </span>
              )}
            </div>
            <div className="flex items-center gap-2">
              {!parcel.isPrimary && (
                <button
                  type="button"
                  onClick={() => setPrimary(i)}
                  className="text-xs font-inter text-green-deep hover:underline cursor-pointer"
                >
                  {t("landSketch.primaryParcel", locale)}
                </button>
              )}
              {parcels.length > 1 && (
                <button type="button" onClick={() => removeParcel(i)} className="text-red-400 hover:text-red-600 cursor-pointer">
                  <Trash2 className="w-4 h-4" />
                </button>
              )}
            </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">
                {t("landSketch.district", locale)}
              </label>
              <select
                value={parcel.district}
                onChange={(e) => updateParcel(i, "district", e.target.value)}
                className={selectClass}
              >
                <option value="" disabled>{t("common.select", locale)}</option>
                {districts.map((d) => (
                  <option key={d.value} value={d.value}>{d.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {t("landSketch.village", locale)}
              </label>
              <input
                type="text"
                value={parcel.village}
                onChange={(e) => updateParcel(i, "village", e.target.value)}
                className={inputClass}
              />
            </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">
                {t("landSketch.areaHa", locale)}
              </label>
              <input
                type="number"
                min="0.1"
                step="0.1"
                value={parcel.areaHa}
                onChange={(e) => updateParcel(i, "areaHa", e.target.value)}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {t("landSketch.landUseType", locale)}
              </label>
              <select
                value={parcel.landUseType}
                onChange={(e) => updateParcel(i, "landUseType", e.target.value)}
                className={selectClass}
              >
                {(["irrigated_cropland", "rainfed", "orchard", "pasture", "greenhouse"] as const).map((lut) => (
                  <option key={lut} value={lut}>{enumLabel("landUseType", lut, locale)}</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">
                {t("landSketch.tenureType", locale)}
              </label>
              <select
                value={parcel.tenureType}
                onChange={(e) => updateParcel(i, "tenureType", e.target.value)}
                className={selectClass}
              >
                {(["owned", "leased", "sharecrop", "communal", "inheritance"] as const).map((tt) => (
                  <option key={tt} value={tt}>{enumLabel("tenureType", tt, locale)}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {t("landSketch.irrigationSource", locale)}
              </label>
              <select
                value={parcel.irrigationSource}
                onChange={(e) => updateParcel(i, "irrigationSource", e.target.value)}
                className={selectClass}
              >
                {(["canal", "well", "drip", "rainfed", "mixed"] as const).map((is) => (
                  <option key={is} value={is}>{enumLabel("irrigationSource", is, locale)}</option>
                ))}
              </select>
            </div>
          </div>

          <div>
            <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
              {t("landSketch.registryRef", locale)}
            </label>
            <input
              type="text"
              value={parcel.registryRef ?? ""}
              onChange={(e) => updateParcel(i, "registryRef", e.target.value)}
              className={inputClass}
            />
          </div>
        </div>
      ))}

      <button
        type="button"
        onClick={addParcel}
        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 || districtsLoading}
        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>
  );
}
