"use client";

import { useState } from "react";
import { Loader2 } from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useApiMutation } from "@/presentation/hooks/use-api-mutation";
import { useT, useLocale } from "@/shared/i18n/client";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import { Badge } from "@/presentation/components/ui/badge";
import { Switch } from "@/presentation/components/ui/switch";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/presentation/components/ui/dialog";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/presentation/components/ui/table";
import type { DonnaClientDetail, DonnaUsageLine } from "@/domain/entities/donna";

interface Props {
  companyId: number | null;
  month: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onChanged: () => void;
}

export function DonnaClientDialog({ companyId, month, open, onOpenChange, onChanged }: Props) {
  const t = useT();
  const locale = useLocale();
  const repo = useRepositories().donnaRepository;
  const [saved, setSaved] = useState<DonnaClientDetail | null>(null);
  const [price, setPrice] = useState("");
  const [customAmount, setCustomAmount] = useState("");
  const [customNote, setCustomNote] = useState("");

  const { data, loading } = useApiQuery(() => repo.findClient(companyId as number, month), {
    enabled: companyId !== null,
    deps: [companyId, month],
  });

  // A fresh load replaces whatever the last action returned.
  const [loaded, setLoaded] = useState(data);
  if (data !== loaded) {
    setLoaded(data);
    setSaved(null);
    setPrice(data?.price_per_vehicle?.toString() ?? "");
  }
  const detail = saved ?? data;

  const money = (amount: number, digits = 2) =>
    new Intl.NumberFormat(locale === "fr" ? "fr-FR" : "en-US", {
      style: "currency", currency: "EUR", minimumFractionDigits: digits, maximumFractionDigits: digits,
    }).format(amount);

  const apply = (next: DonnaClientDetail) => {
    setSaved(next);
    setPrice(next.price_per_vehicle?.toString() ?? "");
    onChanged();
  };

  const update = useApiMutation(
    (payload: { donna_price_per_vehicle?: number | null; donna_gift_enabled?: boolean }) => repo.updateClient(companyId as number, payload),
    { successMessage: t.donna.saved, onSuccess: apply }
  );
  const grant = useApiMutation(() => repo.grantGift(companyId as number), { successMessage: t.donna.detail.granted, onSuccess: apply });
  const revoke = useApiMutation((id: number) => repo.revokeGift(id), { successMessage: t.donna.detail.revokedToast, onSuccess: apply });
  const custom = useApiMutation(
    () => repo.customGift(companyId as number, { amount_eur: Number(customAmount), note: customNote || null }),
    {
      successMessage: t.donna.detail.granted,
      onSuccess: (next) => {
        setCustomAmount("");
        setCustomNote("");
        apply(next);
      },
    }
  );
  const restore = useApiMutation((id: number) => repo.restoreGift(id), { successMessage: t.donna.detail.restoredToast, onSuccess: apply });

  const gift = detail?.donna.gift ?? null;
  const isCurrentMonth = detail?.period === new Date().toISOString().slice(0, 7);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">
        <DialogHeader>
          <DialogTitle>{detail ? t.donna.detail.title(detail.company.name, detail.period) : "…"}</DialogTitle>
        </DialogHeader>

        {loading && !detail ? (
          <div className="flex justify-center py-10">
            <Loader2 className="h-5 w-5 animate-spin" />
          </div>
        ) : detail ? (
          <div className="space-y-6">
            <section className="space-y-3 rounded-md border p-4">
              <div className="flex flex-wrap items-end gap-3">
                <label className="space-y-1 text-sm">
                  <span className="font-medium">{t.donna.detail.priceLabel}</span>
                  <Input type="number" min={0} step="0.01" value={price} onChange={(e) => setPrice(e.target.value)} className="w-32" />
                </label>
                <Button
                  size="sm"
                  disabled={update.loading || price === (detail.price_per_vehicle?.toString() ?? "")}
                  onClick={() => update.mutate({ donna_price_per_vehicle: price === "" ? null : Number(price) })}
                >
                  {t.donna.save}
                </Button>
                <label className="ml-auto flex items-center gap-2 text-sm">
                  <Switch
                    checked={detail.gift_enabled}
                    onCheckedChange={(checked) => update.mutate({ donna_gift_enabled: checked })}
                  />
                  {t.donna.detail.giftEnabled}
                </label>
              </div>
              <p className="text-xs text-muted-foreground">{t.donna.detail.priceHint}</p>
              <p className="text-sm">
                {detail.gift_quote
                  ? t.donna.detail.quote(money(detail.gift_quote.amount_eur), detail.gift_quote.vehicles_count, money(detail.gift_quote.price_per_vehicle))
                  : t.donna.detail.noQuote}
              </p>
              <div className="flex flex-wrap gap-2">
                {!gift && isCurrentMonth && detail.gift_quote && (
                  <Button size="sm" variant="outline" disabled={grant.loading} onClick={() => grant.mutate(undefined)}>
                    {t.donna.detail.grant}
                  </Button>
                )}
                {gift && !gift.revoked && (
                  <Button size="sm" variant="outline" className="text-red-600" disabled={revoke.loading} onClick={() => revoke.mutate(gift.id)}>
                    {t.donna.detail.revoke}
                  </Button>
                )}
                {gift?.revoked && (
                  <Button size="sm" variant="outline" disabled={restore.loading} onClick={() => restore.mutate(gift.id)}>
                    {t.donna.detail.restore}
                  </Button>
                )}
              </div>
              {isCurrentMonth && (
                <div className="space-y-2 border-t pt-3">
                  <p className="text-sm font-medium">{t.donna.detail.customTitle}</p>
                  <p className="text-xs text-muted-foreground">{t.donna.detail.customHint}</p>
                  <div className="flex flex-wrap items-center gap-2">
                    <Input
                      type="number"
                      min={0}
                      step="0.01"
                      value={customAmount}
                      placeholder={t.donna.detail.customAmount}
                      onChange={(e) => setCustomAmount(e.target.value)}
                      className="w-36"
                    />
                    <Input
                      value={customNote}
                      placeholder={t.donna.detail.customNote}
                      onChange={(e) => setCustomNote(e.target.value)}
                      className="min-w-48 flex-1"
                    />
                    <Button size="sm" disabled={custom.loading || !(Number(customAmount) > 0)} onClick={() => custom.mutate(undefined)}>
                      {t.donna.detail.customGrant}
                    </Button>
                  </div>
                  {gift?.custom && gift.note && <p className="text-xs text-muted-foreground">{t.donna.detail.customNoteShown(gift.note)}</p>}
                </div>
              )}
            </section>

            <section className="grid grid-cols-2 gap-3 sm:grid-cols-5">
              <Figure label={t.donna.detail.gift} value={gift ? money(gift.amount_eur) : "—"} muted={gift?.revoked} />
              <Figure label={t.donna.detail.used} value={money(detail.donna.used_eur)} />
              <Figure label={t.donna.detail.remaining} value={money(detail.donna.remaining_eur)} />
              <Figure label={t.donna.detail.overage} value={money(detail.donna.overage_eur)} />
              <Figure label={t.donna.detail.ourCost} value={money(detail.donna.cost_eur + detail.platform.cost_eur, 4)} />
            </section>

            <UsageTable title={t.donna.detail.donnaLines} lines={detail.donna.lines} money={money} />

            <section className="space-y-2">
              <h4 className="text-sm font-semibold">{t.donna.detail.workers}</h4>
              <div className="grid gap-2 sm:grid-cols-2">
                {detail.donna.workers.map((worker) => (
                  <div key={worker.key} className="flex items-center justify-between rounded-md border px-3 py-2 text-sm">
                    <span className="truncate">{worker.label}</span>
                    <span className="flex items-center gap-2">
                      <span className="tabular-nums">{money(worker.price_eur)}</span>
                      {worker.enabled !== null && (
                        <Badge variant={worker.enabled ? "secondary" : "outline"}>
                          {worker.enabled ? t.donna.detail.on : t.donna.detail.off}
                        </Badge>
                      )}
                    </span>
                  </div>
                ))}
              </div>
            </section>

            <UsageTable title={t.donna.detail.platformLines} lines={detail.platform.lines} money={money} />
          </div>
        ) : null}
      </DialogContent>
    </Dialog>
  );
}

function Figure({ label, value, muted }: { label: string; value: string; muted?: boolean }) {
  return (
    <div className="rounded-md border p-3">
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className={`text-lg font-semibold tabular-nums ${muted ? "text-muted-foreground line-through" : ""}`}>{value}</p>
    </div>
  );
}

function UsageTable({ title, lines, money }: { title: string; lines: DonnaUsageLine[]; money: (a: number, d?: number) => string }) {
  const t = useT();

  return (
    <section className="space-y-2">
      <h4 className="text-sm font-semibold">{title}</h4>
      {lines.length === 0 ? (
        <p className="text-sm text-muted-foreground">{t.donna.detail.nothing}</p>
      ) : (
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>{t.donna.detail.feature}</TableHead>
              <TableHead className="text-right">{t.donna.detail.calls}</TableHead>
              <TableHead className="text-right">{t.donna.detail.price}</TableHead>
              <TableHead className="text-right">{t.donna.detail.cost}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {lines.map((line) => (
              <TableRow key={line.feature}>
                <TableCell>{line.label}</TableCell>
                <TableCell className="text-right tabular-nums">{line.calls}</TableCell>
                <TableCell className="text-right tabular-nums">{money(line.price_eur)}</TableCell>
                <TableCell className="text-right tabular-nums text-muted-foreground">{money(line.cost_eur, 4)}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      )}
    </section>
  );
}
