"use client";

import { useActionState, useEffect, useState, useTransition } from "react";
import { Loader2, Trash2 } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { deleteConnectionAction } from "@/lib/appwrite/connection-actions";
import { initialConnectionActionState } from "@/lib/appwrite/connection-types";
import type { ConnectionWithCounterpart } from "@/lib/appwrite/connection-queries";
import type { ClinicPricing, TenantKind } from "@/lib/appwrite/schema";
import { PROSTHETIC_TYPE_OPTIONS } from "@/lib/appwrite/prosthetic-types";
import { ClinicPricingDialog } from "./clinic-pricing-dialog";

const TYPE_LABELS = Object.fromEntries(
  PROSTHETIC_TYPE_OPTIONS.map((o) => [o.value, o.label]),
) as Record<string, string>;

const dateFormatter = new Intl.DateTimeFormat("tr-TR", {
  day: "2-digit",
  month: "2-digit",
  year: "numeric",
});

export function ConnectionsTable({
  rows,
  selfKind,
  pricingByCounterpart = {},
  defaultCurrency = "TRY",
}: {
  rows: ConnectionWithCounterpart[];
  selfKind: TenantKind | null;
  pricingByCounterpart?: Record<string, ClinicPricing[]>;
  defaultCurrency?: string;
}) {
  if (rows.length === 0) {
    return (
      <p className="text-muted-foreground py-6 text-center text-sm">
        Henüz onaylanmış bağlantınız yok. Yukarıdan talep gönderebilir veya kodunuzu paylaşabilirsiniz.
      </p>
    );
  }

  const isLab = selfKind === "lab";

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Karşı taraf</TableHead>
          <TableHead>Tür</TableHead>
          <TableHead>Onay tarihi</TableHead>
          <TableHead>{isLab ? "Fiyat kuralları" : "Sizin için kurallar"}</TableHead>
          <TableHead className="text-right">İşlem</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((r) => {
          const counterpartId = isLab ? r.clinicTenantId : r.labTenantId;
          const pricing = pricingByCounterpart[counterpartId] ?? [];
          return (
            <ApprovedRow
              key={r.$id}
              row={r}
              isLab={isLab}
              pricing={pricing}
              defaultCurrency={defaultCurrency}
            />
          );
        })}
      </TableBody>
    </Table>
  );
}

function ApprovedRow({
  row,
  isLab,
  pricing,
  defaultCurrency,
}: {
  row: ConnectionWithCounterpart;
  isLab: boolean;
  pricing: ClinicPricing[];
  defaultCurrency: string;
}) {
  const [state, action, pending] = useActionState(
    deleteConnectionAction,
    initialConnectionActionState,
  );
  const [, startTransition] = useTransition();
  const [open, setOpen] = useState(false);

  useEffect(() => {
    if (state.ok) {
      toast.success("Bağlantı silindi.");
      setOpen(false);
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state]);

  const kindLabel =
    row.counterpart?.kind === "lab"
      ? "Laboratuvar"
      : row.counterpart?.kind === "clinic"
        ? "Klinik"
        : "—";

  const counterpartId = isLab ? row.clinicTenantId : row.labTenantId;

  return (
    <TableRow>
      <TableCell className="font-medium">{row.counterpart?.companyName ?? "—"}</TableCell>
      <TableCell>
        <Badge variant="secondary">{kindLabel}</Badge>
      </TableCell>
      <TableCell className="text-muted-foreground">
        {row.approvedAt ? dateFormatter.format(new Date(row.approvedAt)) : "—"}
      </TableCell>
      <TableCell className="text-muted-foreground text-xs">
        {pricing.length === 0 ? (
          <span>Katalog fiyatı</span>
        ) : (
          <ul className="space-y-0.5">
            {pricing.slice(0, 3).map((p) => (
              <li key={p.$id}>
                <span className="text-foreground">
                  {TYPE_LABELS[p.prostheticType] ?? p.prostheticType}
                </span>
                {": "}
                {p.customUnitPrice !== undefined && p.customUnitPrice !== null
                  ? `${p.customUnitPrice} ${p.currency || defaultCurrency}`
                  : p.discountPercent
                    ? `%${p.discountPercent} indirim`
                    : "—"}
              </li>
            ))}
            {pricing.length > 3 && <li>+ {pricing.length - 3} kural</li>}
          </ul>
        )}
      </TableCell>
      <TableCell className="text-right">
        <div className="flex justify-end gap-2">
          {isLab && (
            <ClinicPricingDialog
              clinicTenantId={counterpartId}
              clinicName={row.counterpart?.companyName ?? "Klinik"}
              rows={pricing}
              defaultCurrency={defaultCurrency}
            />
          )}
        <Dialog open={open} onOpenChange={setOpen}>
          <DialogTrigger asChild>
            <Button size="sm" variant="outline">
              <Trash2 className="size-4" />
              Sil
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Bağlantı silinsin mi?</DialogTitle>
              <DialogDescription>
                {row.counterpart?.companyName ?? "Karşı taraf"} ile bağlantınız sonlandırılacak.
                Mevcut işleriniz etkilenmez ancak yeni iş gönderemezsiniz.
              </DialogDescription>
            </DialogHeader>
            <DialogFooter>
              <DialogClose asChild>
                <Button type="button" variant="outline">Vazgeç</Button>
              </DialogClose>
              <form
                action={(fd) => {
                  startTransition(() => action(fd));
                }}
              >
                <input type="hidden" name="connectionId" value={row.$id} />
                <Button type="submit" disabled={pending} variant="destructive">
                  {pending ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
                  Sil
                </Button>
              </form>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        </div>
      </TableCell>
    </TableRow>
  );
}
