"use client";

import { useState } from "react";
import {
  HandCoins,
  AlertCircle,
  ChevronDown,
  ChevronUp,
} from "lucide-react";
import type { FinanceViewModel, IdentityViewModel, TradeViewModel } from "@/lib/farmer-dashboard";
import { getFarmerExplanationText } from "@/lib/scoring-reasons";
import { useLocale } from "@/lib/i18n";
import { tf } from "@/lib/i18n/dashboard-labels";
import type { AppLocale } from "@/lib/i18n/config";
import { Card, CardHeader, CardTitle } from "@/components/ui/card";
import {
  ApprovalPathStepper,
  BankRoutingList,
  CaseHeaderMetrics,
  DocumentChecklist,
  FarmerFarmCard,
} from "@/components/agnet/finance";

interface Props {
  data: FinanceViewModel | null;
  identity?: IdentityViewModel | null;
  trade?: TradeViewModel | null;
}

export default function FinanceModule({ data, identity, trade }: Props) {
  const { locale } = useLocale();
  const [showExplanation, setShowExplanation] = useState(false);

  if (!data) {
    return <EmptyState locale={locale} />;
  }

  const explanationText = getFarmerExplanationText(data.farmerExplanation, locale);
  const gisVerified = identity?.hasGisMapping ?? false;
  const primaryCrop = trade?.crops?.[0]?.crop;
  const season = trade?.crops?.[0]?.season;

  return (
    <div
      className="relative mx-auto max-w-[1400px] space-y-6"
      data-testid="finance-module"
    >
      <div
        className="pointer-events-none absolute inset-0 -z-10 overflow-hidden rounded-2xl opacity-[0.07]"
        aria-hidden="true"
      >
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src="/agnet-assets/agnet-finance-dashboard.png"
          alt=""
          className="h-full w-full object-cover object-top"
        />
      </div>

      <CaseHeaderMetrics finance={data} gisVerified={gisVerified} locale={locale} />

      <div className="grid grid-cols-1 gap-4 xl:grid-cols-3">
        {identity ? (
          <FarmerFarmCard
            identity={identity}
            finance={data}
            primaryCrop={primaryCrop}
            season={season}
            gisVerified={gisVerified}
            locale={locale}
            className="xl:col-span-1"
          />
        ) : null}

        {data.bankMatches && data.bankMatches.length > 0 ? (
          <BankRoutingList matches={data.bankMatches} locale={locale} />
        ) : null}

        {data.documents && data.documents.length > 0 ? (
          <DocumentChecklist documents={data.documents} locale={locale} />
        ) : null}
      </div>

      {data.stages.length > 0 ? (
        <ApprovalPathStepper stages={data.stages} locale={locale} />
      ) : null}

      {explanationText ? (
        <Card padding="md">
          <button
            type="button"
            onClick={() => setShowExplanation((v) => !v)}
            className="flex w-full cursor-pointer items-center justify-between gap-2 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-green-deep focus-visible:ring-offset-2"
            aria-expanded={showExplanation}
          >
            <span className="font-onest text-base font-semibold text-ink">
              {tf("whyScore", locale)}
            </span>
            {showExplanation ? (
              <ChevronUp className="size-5 shrink-0 text-muted" />
            ) : (
              <ChevronDown className="size-5 shrink-0 text-muted" />
            )}
          </button>
          {showExplanation ? (
            <p className="mt-3 font-inter text-sm leading-relaxed text-ink-soft">
              {explanationText}
            </p>
          ) : null}
        </Card>
      ) : null}

      <div className="flex items-start gap-3 rounded-card border border-amber-200 bg-amber-50 p-4 dark:border-amber-700/30 dark:bg-amber-900/20">
        <AlertCircle className="mt-0.5 size-5 shrink-0 text-amber-600 dark:text-amber-400" />
        <p className="font-inter text-sm text-amber-800 dark:text-amber-200">
          {tf("routingNotice", locale)}
        </p>
      </div>
    </div>
  );
}

function EmptyState({ locale }: { locale: AppLocale }) {
  return (
    <div className="py-12 text-center" data-testid="finance-empty-state">
      <div className="mx-auto mb-4 flex size-12 items-center justify-center rounded-full bg-[var(--glass)]">
        <HandCoins className="size-6 text-muted" />
      </div>
      <h3 className="font-onest text-lg font-semibold text-ink">{tf("emptyTitle", locale)}</h3>
      <p className="mx-auto mt-1 max-w-sm font-inter text-sm text-muted">
        {tf("emptyDesc", locale)}
      </p>
    </div>
  );
}
