"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { DotsThree, Plus, PencilSimple, Trash } from '@/lib/icons';
import { toast } from "sonner";

import { Button } from "@/components/ui/button";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { deleteInvestorAction } from "@/lib/appwrite/investor-actions";
import { InvestorFormSheet } from "./investor-form-sheet";
import { DeleteConfirmDialog } from "@/components/ui/delete-confirm-dialog";
import type { Investor } from "@/lib/appwrite/schema";

interface InvestorsClientProps {
  initialInvestors: Investor[];
}

export function InvestorsClient({ initialInvestors }: InvestorsClientProps) {
  const router = useRouter();
  const [investors, setInvestors] = useState(initialInvestors);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [editing, setEditing] = useState<Investor | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Investor | null>(null);

  function openCreate() { setEditing(null); setSheetOpen(true); }
  function openEdit(i: Investor) { setEditing(i); setSheetOpen(true); }

  async function doDelete() {
    if (!deleteTarget) return;
    const result = await deleteInvestorAction(deleteTarget.$id);
    if (result.ok) {
      setInvestors((prev) => prev.filter((x) => x.$id !== deleteTarget.$id));
      setDeleteTarget(null);
      toast.success("Yatırımcı silindi.");
    } else {
      toast.error(result.error ?? "Silinemedi.");
    }
  }

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Yatırımcılar</h1>
        <Button onClick={openCreate} size="sm">
          <Plus className="mr-1.5 size-4" />
          Yeni Yatırımcı
        </Button>
      </div>

      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Ad Soyad</TableHead>
              <TableHead>Email</TableHead>
              <TableHead>Telefon</TableHead>
              <TableHead className="text-right">Bütçe</TableHead>
              <TableHead />
            </TableRow>
          </TableHeader>
          <TableBody>
            {investors.length === 0 && (
              <TableRow>
                <TableCell colSpan={5} className="text-muted-foreground text-center py-10">
                  Henüz yatırımcı yok.
                </TableCell>
              </TableRow>
            )}
            {investors.map((i) => (
              <TableRow key={i.$id}>
                <TableCell className="font-medium">{i.name}</TableCell>
                <TableCell>{i.email}</TableCell>
                <TableCell className="text-muted-foreground">{i.phone ?? "—"}</TableCell>
                <TableCell className="text-right tabular-nums">
                  {i.budget ? `${i.budget.toLocaleString("tr-TR")} ${i.currency ?? "TRY"}` : "—"}
                </TableCell>
                <TableCell>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="size-8">
                        <DotsThree className="size-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem onClick={() => openEdit(i)}>
                        <PencilSimple className="mr-2 size-4" />
                        Düzenle
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => setDeleteTarget(i)}
                        className="text-destructive focus:text-destructive"
                      >
                        <Trash className="mr-2 size-4" />
                        Sil
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <InvestorFormSheet
        open={sheetOpen}
        onOpenChange={setSheetOpen}
        investor={editing}
        onSuccess={() => router.refresh()}
      />
      <DeleteConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(v) => { if (!v) setDeleteTarget(null); }}
        title={`"${deleteTarget?.name}" silinsin mi?`}
        description="Bu yatırımcı kalıcı olarak silinecek ve geri alınamaz."
        onConfirm={doDelete}
      />
    </div>
  );
}
