"use client";

import { useState } from "react";
import { ArrowUpRight, Plus, Trash2, AlertTriangle } from "lucide-react";
import type { CropEntry, CropSeason, StepCropPlanData } from "@/lib/api-types";
import { enumLabel, t, type WizardLocale } from "@/lib/i18n/wizard-labels";
import {
  getCropPlanValidationIssues,
  isCropPlanComplete,
  type CropPlanField,
} from "@/lib/crop-plan-validation";
import { useReferenceOptions } from "../hooks/useReferenceOptions";

interface Props {
  data: Partial<StepCropPlanData>;
  loading: boolean;
  locale?: WizardLocale;
  totalLandHa?: number;
  onSave: (data: StepCropPlanData) => Promise<unknown>;
  onSaveDraft: (data: Partial<StepCropPlanData>) => Promise<unknown>;
}

interface CropForm {
  crop: string;
  season: CropSeason;
  areaHa: string;
  expectedYield: string;
  intendedMarket: string;
  hasBuyerContract: boolean;
  priorYearYield: string;
}

const emptyCrop = (): CropForm => ({
  crop: "",
  season: "spring",
  areaHa: "",
  expectedYield: "",
  intendedMarket: "",
  hasBuyerContract: false,
  priorYearYield: "",
});

export default function StepCropPlan({
  data,
  loading,
  locale = "uz",
  totalLandHa = 0,
  onSave,
}: Props) {
  const { options: cropOptions, loading: optionsLoading, error: optionsError } = useReferenceOptions("crops", "UZ", {
    locale,
  });
  const [crops, setCrops] = useState<CropForm[]>(
    data?.crops?.length
      ? data.crops.map((c) => ({
          crop: c.crop,
          season: c.season,
          areaHa: String(c.areaHa ?? ""),
          expectedYield: String(c.expectedYield ?? ""),
          intendedMarket: c.intendedMarket ?? "",
          hasBuyerContract: c.hasBuyerContract ?? false,
          priorYearYield: c.priorYearYield != null ? String(c.priorYearYield) : "",
        }))
      : [emptyCrop()],
  );

  const cropAreaSum = crops.reduce((sum, c) => sum + (Number(c.areaHa) || 0), 0);
  const areaExceeded = totalLandHa > 0 && cropAreaSum > totalLandHa + 0.001;
  const areaRemaining = totalLandHa > 0 ? Math.max(totalLandHa - cropAreaSum, 0) : null;

  const addCrop = () => setCrops((prev) => [...prev, emptyCrop()]);
  const removeCrop = (i: number) => setCrops((prev) => prev.filter((_, idx) => idx !== i));
  const updateCrop = (i: number, field: keyof CropForm, value: string | boolean) =>
    setCrops((prev) => prev.map((c, idx) => (idx === i ? { ...c, [field]: value } : c)));

  const cropFormSlices = crops.map((c) => ({
    crop: c.crop,
    areaHa: c.areaHa,
    expectedYield: c.expectedYield,
  }));
  const validationIssues = getCropPlanValidationIssues(cropFormSlices, totalLandHa);
  const isValid = isCropPlanComplete(cropFormSlices, totalLandHa);
  const missingIssues = validationIssues.filter((issue) => issue.kind === "missing");
  const hasAreaExceeded = validationIssues.some((issue) => issue.kind === "areaExceeded");

  const fieldLabel = (field: CropPlanField) => {
    if (field === "crop") return t("cropPlan.crop", locale);
    if (field === "areaHa") return t("cropPlan.areaHa", locale);
    return t("cropPlan.expectedYield", locale);
  };

  const handleSave = () => {
    const payload: CropEntry[] = crops.map((c) => ({
      crop: c.crop,
      season: c.season,
      areaHa: Number(c.areaHa),
      expectedYield: Number(c.expectedYield),
      ...(c.intendedMarket ? { intendedMarket: c.intendedMarket } : {}),
      ...(c.hasBuyerContract ? { hasBuyerContract: true } : {}),
      ...(c.priorYearYield ? { priorYearYield: Number(c.priorYearYield) } : {}),
    }));
    onSave({ crops: payload });
  };

  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("cropPlan.title", locale)}</h2>
        <p className="mt-1 font-inter text-sm text-ink-soft">{t("cropPlan.subtitle", locale)}</p>
      </div>

      {optionsError && (
        <div className="rounded-xl border border-red-200 bg-red-50 dark:border-red-700/30 dark:bg-red-900/20 px-4 py-3 text-sm text-red-700 dark:text-red-400 font-inter">
          {optionsError}
        </div>
      )}

      {totalLandHa > 0 && (
        <div className={`flex items-center gap-2 px-4 py-2.5 rounded-xl border ${
          areaExceeded ? "border-amber-200 bg-amber-50" : "border-border bg-green-deep/[0.02]"
        }`}>
          {areaExceeded && <AlertTriangle className="w-4 h-4 text-amber-600 shrink-0" />}
          <p className={`font-inter text-xs ${areaExceeded ? "text-amber-700" : "text-ink/60"}`}>
            {areaExceeded
              ? `${t("cropPlan.areaWarning", locale)} (${cropAreaSum.toFixed(1)} / ${totalLandHa.toFixed(1)} ha)`
              : `${t("cropPlan.areaRemaining", locale)}: ${areaRemaining?.toFixed(1)} ha / ${totalLandHa.toFixed(1)} ha`}
          </p>
        </div>
      )}

      {crops.map((crop, 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">
              {t("cropPlan.crop", locale)} {i + 1}
            </span>
            {crops.length > 1 && (
              <button type="button" onClick={() => removeCrop(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">
                {t("cropPlan.crop", locale)} *
              </label>
              <select
                value={crop.crop}
                onChange={(e) => updateCrop(i, "crop", e.target.value)}
                className={selectClass}
              >
                <option value="" disabled>{t("common.select", locale)}</option>
                {cropOptions.map((c) => (
                  <option key={c.value} value={c.value}>{c.label}</option>
                ))}
              </select>
            </div>
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {t("cropPlan.season", locale)}
              </label>
              <select
                value={crop.season}
                onChange={(e) => updateCrop(i, "season", e.target.value)}
                className={selectClass}
              >
                {(["spring", "summer", "autumn", "winter"] as const).map((s) => (
                  <option key={s} value={s}>{enumLabel("season", s, 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("cropPlan.areaHa", locale)} *
              </label>
              <input
                type="number"
                min="0"
                step="0.1"
                value={crop.areaHa}
                onChange={(e) => updateCrop(i, "areaHa", e.target.value)}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {t("cropPlan.expectedYield", locale)} *
              </label>
              <input
                type="number"
                min="0"
                step="0.1"
                value={crop.expectedYield}
                onChange={(e) => updateCrop(i, "expectedYield", 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">
                {locale === "ru" ? "Целевой рынок" : "Maqsadli bozor"}
              </label>
              <input
                type="text"
                placeholder={locale === "ru" ? "Экспорт, опт..." : "Eksport, ulgurji..."}
                value={crop.intendedMarket}
                onChange={(e) => updateCrop(i, "intendedMarket", e.target.value)}
                className={inputClass}
              />
            </div>
            <div>
              <label className="block font-inter text-xs font-medium text-ink/60 mb-1">
                {locale === "ru" ? "Урожай прошлого года (т)" : "O'tgan yil hosili (t)"}
              </label>
              <input
                type="number"
                min="0"
                step="0.1"
                value={crop.priorYearYield}
                onChange={(e) => updateCrop(i, "priorYearYield", e.target.value)}
                className={inputClass}
              />
            </div>
          </div>
          <label className="flex items-center gap-2 cursor-pointer">
            <input
              type="checkbox"
              checked={crop.hasBuyerContract}
              onChange={(e) => updateCrop(i, "hasBuyerContract", 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" ? "Есть договор с покупателем" : "Xaridor bilan shartnoma bor"}
            </span>
          </label>
        </div>
      ))}

      <button
        type="button"
        onClick={addCrop}
        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>

      {!isValid && !loading && !optionsLoading && (missingIssues.length > 0 || hasAreaExceeded) && (
        <div className="rounded-xl border border-amber-200 bg-amber-50 dark:border-amber-700/30 dark:bg-amber-900/20 px-4 py-3">
          <p className="font-inter text-sm font-medium text-amber-900">
            {t("cropPlan.completeRequiredHint", locale)}
          </p>
          <ul className="mt-2 list-disc list-inside font-inter text-sm text-amber-800 space-y-0.5">
            {hasAreaExceeded && <li>{t("cropPlan.reduceAreaHint", locale)}</li>}
            {missingIssues.map((issue) => (
              <li key={`${issue.cropIndex}-${issue.field}`}>
                {t("cropPlan.crop", locale)} {issue.cropIndex + 1}: {fieldLabel(issue.field)}
              </li>
            ))}
          </ul>
        </div>
      )}

      <button
        type="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>
  );
}
