"use client";

import { useMemo, useState } from "react";
import { ArrowUpRight, ChevronRight, AlertTriangle } from "lucide-react";
import type {
  ConflictResolution,
  OnboardingStepData,
  ReviewConflict,
  StepReviewData,
} from "@/lib/api-types";
import { formatUzs } from "@/lib/fx-snapshot";
import {
  allConflictsResolved,
  detectReviewConflicts,
} from "@/lib/review-conflicts";
import { enumLabel, t, type WizardLocale } from "@/lib/i18n/wizard-labels";
import { getDistrictLabel, getRegionLabel } from "@/lib/reference-data/regions";

interface Props {
  data: Partial<StepReviewData>;
  loading: boolean;
  locale?: WizardLocale;
  onSave: (data: StepReviewData) => Promise<unknown>;
  onSaveDraft: (data: Partial<StepReviewData>) => Promise<unknown>;
  allStepData: OnboardingStepData;
  onSubmitForProcessing: () => Promise<unknown>;
}

interface SummaryGroup {
  key: string;
  title: string;
  lines: string[];
}

function buildSummaryGroups(stepData: OnboardingStepData, locale: WizardLocale): SummaryGroup[] {
  const profile = stepData.FARM_PROFILE;
  const land = stepData.LAND_SKETCH;
  const crops = stepData.CROP_PLAN;
  const assets = stepData.FARM_ASSETS;
  const finance = stepData.FINANCE_REQUEST;
  const documents = stepData.DOCUMENTS;

  const identityLines: string[] = [];
  if (profile?.fullName) identityLines.push(profile.fullName);
  if (profile?.region) {
    identityLines.push(getRegionLabel(profile.region, locale) ?? profile.region);
  }
  if (profile?.district) {
    identityLines.push(getDistrictLabel(profile.district, locale) ?? profile.district);
  }
  if (profile?.farmerType) {
    identityLines.push(enumLabel("farmerType", profile.farmerType, locale));
  }

  const landLines: string[] = [];
  land?.parcels?.forEach((p) => {
    const label = getDistrictLabel(p.district, locale) ?? p.district;
    landLines.push(
      `${p.isPrimary ? "★ " : ""}${label}: ${p.areaHa} ha — ${enumLabel("landUseType", p.landUseType, locale)}`,
    );
  });

  const cropLines: string[] = [];
  crops?.crops?.forEach((c) => {
    const market = c.intendedMarket ? ` → ${c.intendedMarket}` : "";
    cropLines.push(`${c.crop}: ${c.areaHa} ha (${enumLabel("season", c.season, locale)})${market}`);
  });

  const assetLines: string[] = [];
  if (assets?.noneDeclared) {
    assetLines.push(locale === "ru" ? "Активы не заявлены" : "Aktivlar e'lon qilinmagan");
  } else {
    assets?.assets?.forEach((a) => {
      assetLines.push(`${a.assetType} ×${a.quantity}`);
    });
    if (assets?.storageCapacity) {
      assetLines.push(
        locale === "ru"
          ? `Ёмкость хранения: ${assets.storageCapacity} т`
          : `Saqlash sig'imi: ${assets.storageCapacity} t`,
      );
    }
  }

  const financeLines: string[] = [];
  if (finance?.purpose) financeLines.push(finance.purpose);
  if (finance?.amountUzs) financeLines.push(`${formatUzs(finance.amountUzs)} so'm`);
  if (finance?.termMonths) {
    financeLines.push(`${finance.termMonths} ${locale === "ru" ? "мес." : "oy"}`);
  }
  if (finance?.expectedRevenueUzs) {
    financeLines.push(
      locale === "ru"
        ? `Ожид. доход: ${formatUzs(finance.expectedRevenueUzs)}`
        : `Kutil. daromad: ${formatUzs(finance.expectedRevenueUzs)}`,
    );
  }

  const docLines: string[] = [];
  const uploaded = documents?.uploaded ?? {};
  Object.entries(uploaded).forEach(([key, done]) => {
    if (done) docLines.push(key.replace(/_/g, " "));
  });

  return [
    { key: "identity", title: t("review.identity", locale), lines: identityLines },
    { key: "land", title: t("review.land", locale), lines: landLines },
    { key: "crops", title: t("review.crops", locale), lines: cropLines },
    { key: "assets", title: t("review.assets", locale), lines: assetLines },
    { key: "finance", title: t("review.finance", locale), lines: financeLines },
    { key: "documents", title: t("review.documents", locale), lines: docLines },
  ];
}

const RESOLUTION_OPTIONS: { value: ConflictResolution; labelUz: string; labelRu: string }[] = [
  { value: "keep_mine", labelUz: "Mening ma'lumotimni saqlash", labelRu: "Оставить мои данные" },
  { value: "use_document", labelUz: "Hujjatdagi ma'lumotni ishlatish", labelRu: "Использовать из документа" },
  { value: "edit", labelUz: "Keyinroq tahrirlash", labelRu: "Исправить позже" },
];

export default function StepReview({
  allStepData,
  loading,
  locale = "uz",
  onSave,
  onSubmitForProcessing,
}: Props) {
  const [attestationChecked, setAttestationChecked] = useState(false);
  const detected = useMemo(() => detectReviewConflicts(allStepData), [allStepData]);
  const [conflicts, setConflicts] = useState<ReviewConflict[]>(detected);
  const groups = buildSummaryGroups(allStepData, locale);
  const attestationText = t("review.attestation", locale);
  const conflictsOk = conflicts.length === 0 || allConflictsResolved(conflicts);

  const setResolution = (id: string, resolution: ConflictResolution) => {
    setConflicts((prev) => prev.map((c) => (c.id === id ? { ...c, resolution } : c)));
  };

  const handleSubmit = async () => {
    await onSave({
      reviewed: true,
      reviewedAt: new Date().toISOString(),
      attestationText,
      conflicts: conflicts.length > 0 ? conflicts : undefined,
    });
    await onSubmitForProcessing();
  };

  return (
    <div className="space-y-5">
      <div>
        <h2 className="font-onest text-2xl font-semibold text-ink">{t("review.title", locale)}</h2>
        <p className="mt-1 font-inter text-sm text-ink-soft">{t("review.subtitle", locale)}</p>
      </div>

      {conflicts.length > 0 && (
        <div className="rounded-xl border border-amber-200 bg-amber-50 dark:border-amber-700/30 dark:bg-amber-900/20 p-4 space-y-3">
          <div className="flex items-center gap-2">
            <AlertTriangle className="w-4 h-4 text-amber-600 shrink-0" />
            <h3 className="font-onest text-sm font-semibold text-amber-900">
              {locale === "ru" ? "Обнаружены расхождения" : "Nomuvofiqliklar aniqlandi"}
            </h3>
          </div>
          {conflicts.map((c) => (
            <div key={c.id} className="rounded-lg bg-surface/80 p-3 space-y-2">
              <p className="font-inter text-xs text-ink-soft">{c.label}</p>
              <p className="font-inter text-[10px] text-muted">
                {locale === "ru" ? "Ваша запись" : "Sizning ma'lumotingiz"}: {c.farmerValue} ·{" "}
                {locale === "ru" ? "Документ/OCR" : "Hujjat/OCR"}: {c.documentValue}
              </p>
              <div className="flex flex-wrap gap-2">
                {RESOLUTION_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setResolution(c.id, opt.value)}
                    className={`px-3 py-1 rounded-full text-[10px] font-inter font-medium cursor-pointer ${
                      c.resolution === opt.value
                        ? "bg-green-deep text-white"
                        : "border border-border text-ink-soft"
                    }`}
                  >
                    {locale === "ru" ? opt.labelRu : opt.labelUz}
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="space-y-3">
        {groups.map((group) => (
          <div
            key={group.key}
            className="rounded-xl border border-border bg-surface p-4"
          >
            <div className="flex items-center justify-between mb-2">
              <h3 className="font-onest text-sm font-semibold text-ink">{group.title}</h3>
              <ChevronRight className="w-4 h-4 text-muted/50" />
            </div>
            {group.lines.length > 0 ? (
              <ul className="space-y-1">
                {group.lines.map((line, i) => (
                  <li key={i} className="font-inter text-xs text-ink-soft">{line}</li>
                ))}
              </ul>
            ) : (
              <p className="font-inter text-xs text-muted/70">{t("common.pending", locale)}</p>
            )}
          </div>
        ))}
      </div>

      <label className="flex items-start gap-3 p-4 rounded-xl border border-green-deep/15 bg-green-deep/5 cursor-pointer">
        <input
          type="checkbox"
          checked={attestationChecked}
          onChange={(e) => setAttestationChecked(e.target.checked)}
          className="mt-0.5 w-5 h-5 rounded border-border text-green-deep focus:ring-green-deep/20 cursor-pointer"
        />
        <span className="font-inter text-sm text-ink-soft leading-relaxed">{attestationText}</span>
      </label>

      <button
        onClick={handleSubmit}
        disabled={loading || !attestationChecked || !conflictsOk}
        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("review.submitting", locale) : t("review.submit", locale)}
        <ArrowUpRight className="w-4 h-4" />
      </button>
    </div>
  );
}
