"use client";

import { useActionState, useEffect, useState, useTransition } from "react";
import { Archive, ArchiveRestore, Loader2, Pencil } 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,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import {
  archivePatientAction,
  updatePatientAction,
} from "@/lib/appwrite/patient-actions";
import {
  initialPatientActionState,
  initialPatientFormState,
} from "@/lib/appwrite/patient-types";
import type { Patient } from "@/lib/appwrite/schema";

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

export function PatientsTable({ rows }: { rows: Patient[] }) {
  if (rows.length === 0) {
    return (
      <p className="text-muted-foreground py-6 text-center text-sm">
        Henüz hasta yok. Sağdaki formdan ekleyebilirsiniz.
      </p>
    );
  }

  return (
    <Table>
      <TableHeader>
        <TableRow>
          <TableHead>Kod</TableHead>
          <TableHead>Ad Soyad</TableHead>
          <TableHead>Telefon</TableHead>
          <TableHead>Doğum</TableHead>
          <TableHead>Durum</TableHead>
          <TableHead className="text-right">İşlem</TableHead>
        </TableRow>
      </TableHeader>
      <TableBody>
        {rows.map((p) => (
          <PatientRow key={p.$id} row={p} />
        ))}
      </TableBody>
    </Table>
  );
}

function PatientRow({ row }: { row: Patient }) {
  const [archiveState, archiveAction, archivePending] = useActionState(
    archivePatientAction,
    initialPatientActionState,
  );
  const [, startTransition] = useTransition();
  const [editOpen, setEditOpen] = useState(false);

  useEffect(() => {
    if (archiveState.ok) {
      toast.success(row.archived ? "Hasta aktifleştirildi." : "Hasta arşivlendi.");
    } else if (archiveState.error) {
      toast.error(archiveState.error);
    }
  }, [archiveState, row.archived]);

  return (
    <TableRow className={row.archived ? "opacity-60" : ""}>
      <TableCell className="font-mono text-xs">{row.patientCode}</TableCell>
      <TableCell className="font-medium">
        {row.firstName} {row.lastName}
      </TableCell>
      <TableCell className="text-muted-foreground">{row.phone || "—"}</TableCell>
      <TableCell className="text-muted-foreground">
        {row.dateOfBirth ? dateFormatter.format(new Date(row.dateOfBirth)) : "—"}
      </TableCell>
      <TableCell>
        {row.archived ? (
          <Badge variant="outline">Arşiv</Badge>
        ) : (
          <Badge variant="secondary">Aktif</Badge>
        )}
      </TableCell>
      <TableCell className="text-right">
        <div className="flex justify-end gap-1.5">
          <Button size="sm" variant="outline" onClick={() => setEditOpen(true)}>
            <Pencil className="size-4" />
          </Button>
          <form
            action={(fd) => {
              startTransition(() => archiveAction(fd));
            }}
          >
            <input type="hidden" name="id" value={row.$id} />
            <Button type="submit" size="sm" variant="outline" disabled={archivePending}>
              {archivePending ? (
                <Loader2 className="size-4 animate-spin" />
              ) : row.archived ? (
                <ArchiveRestore className="size-4" />
              ) : (
                <Archive className="size-4" />
              )}
            </Button>
          </form>
        </div>
        <EditPatientDialog row={row} open={editOpen} onOpenChange={setEditOpen} />
      </TableCell>
    </TableRow>
  );
}

function EditPatientDialog({
  row,
  open,
  onOpenChange,
}: {
  row: Patient;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const [state, action, pending] = useActionState(
    updatePatientAction,
    initialPatientFormState,
  );

  useEffect(() => {
    if (state.ok) {
      toast.success("Hasta güncellendi.");
      onOpenChange(false);
    } else if (state.error) {
      toast.error(state.error);
    }
  }, [state, onOpenChange]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Hasta Bilgileri</DialogTitle>
          <DialogDescription>
            Protokol kodu ({row.patientCode}) değiştirilemez — geçmiş işlerle bağı kopar.
          </DialogDescription>
        </DialogHeader>
        <form action={action} className="grid gap-4">
          <input type="hidden" name="id" value={row.$id} />
          <input type="hidden" name="patientCode" value={row.patientCode} />
          <div className="grid grid-cols-2 gap-3">
            <div className="grid gap-2">
              <Label htmlFor={`first-${row.$id}`}>Ad *</Label>
              <Input
                id={`first-${row.$id}`}
                name="firstName"
                defaultValue={row.firstName}
                required
                maxLength={100}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor={`last-${row.$id}`}>Soyad *</Label>
              <Input
                id={`last-${row.$id}`}
                name="lastName"
                defaultValue={row.lastName}
                required
                maxLength={100}
              />
            </div>
          </div>
          <div className="grid gap-2">
            <Label htmlFor={`phone-${row.$id}`}>Telefon</Label>
            <Input
              id={`phone-${row.$id}`}
              name="phone"
              type="tel"
              defaultValue={row.phone ?? ""}
              maxLength={30}
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor={`dob-${row.$id}`}>Doğum Tarihi</Label>
            <Input
              id={`dob-${row.$id}`}
              name="dateOfBirth"
              type="date"
              defaultValue={row.dateOfBirth ? row.dateOfBirth.slice(0, 10) : ""}
            />
          </div>
          <div className="grid gap-2">
            <Label htmlFor={`notes-${row.$id}`}>Notlar</Label>
            <Textarea
              id={`notes-${row.$id}`}
              name="notes"
              rows={3}
              defaultValue={row.notes ?? ""}
              maxLength={2000}
            />
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button type="button" variant="outline">
                Vazgeç
              </Button>
            </DialogClose>
            <Button type="submit" disabled={pending}>
              {pending ? <Loader2 className="size-4 animate-spin" /> : <Pencil className="size-4" />}
              Kaydet
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
