"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { DotsThree, Plus, PencilSimple, Trash, ArrowSquareOut, Copy } 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 { deletePresentationAction } from "@/lib/appwrite/presentation-actions";
import { PresentationFormSheet } from "./presentation-form-sheet";
import { DeleteConfirmDialog } from "@/components/ui/delete-confirm-dialog";
import { UsageBadge } from "@/components/ui/usage-badge";
import type { Customer, Presentation, Property } from "@/lib/appwrite/schema";

interface PresentationsClientProps {
  initialPresentations: Presentation[];
  customers: Customer[];
  properties: Property[];
  isOwner?: boolean;
  usageLimit?: { current: number; limit: number };
}

export function PresentationsClient({
  initialPresentations,
  customers,
  properties,
  isOwner,
  usageLimit,
}: PresentationsClientProps) {
  const router = useRouter();
  const [presentations, setPresentations] = useState(initialPresentations);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [editing, setEditing] = useState<Presentation | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Presentation | null>(null);

  const appUrl = typeof window !== "undefined" ? window.location.origin : "";

  function getShareUrl(p: Presentation) {
    return `${appUrl}/sunum/${p.shareToken}`;
  }

  function customerName(id?: string | null) {
    if (!id) return "—";
    return customers.find((c) => c.$id === id)?.name ?? id;
  }

  function propertyCount(p: Presentation) {
    try {
      return (JSON.parse(p.propertyIds) as string[]).length;
    } catch {
      return 0;
    }
  }

  useEffect(() => {
    const open = () => { setEditing(null); setSheetOpen(true); };
    const close = () => setSheetOpen(false);
    window.addEventListener("kovak:open-form-presentations", open);
    window.addEventListener("kovak:close-form-presentations", close);
    return () => {
      window.removeEventListener("kovak:open-form-presentations", open);
      window.removeEventListener("kovak:close-form-presentations", close);
    };
  }, []);

  function openCreate() { setEditing(null); setSheetOpen(true); }
  function openEdit(p: Presentation) { setEditing(p); setSheetOpen(true); }

  async function copyLink(p: Presentation) {
    await navigator.clipboard.writeText(getShareUrl(p));
    toast.success("Link kopyalandı.");
  }

  async function doDelete() {
    if (!deleteTarget) return;
    const result = await deletePresentationAction(deleteTarget.$id);
    if (result.ok) {
      setPresentations((prev) => prev.filter((x) => x.$id !== deleteTarget.$id));
      setDeleteTarget(null);
      toast.success("Sunum silindi.");
    } else {
      toast.error(result.error ?? "Silinemedi.");
    }
  }

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <h1 className="text-2xl font-bold">Sunumlar</h1>
        <div className="flex items-center gap-2">
          {isOwner && usageLimit && (
            <UsageBadge current={usageLimit.current} limit={usageLimit.limit} label="sunum" />
          )}
          <Button onClick={openCreate} size="sm" data-tour="presentations-add">
            <Plus className="mr-1.5 size-4" />
            Yeni Sunum
          </Button>
        </div>
      </div>

      <div data-tour="presentations-table" className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Başlık</TableHead>
              <TableHead>Müşteri</TableHead>
              <TableHead>İlanlar</TableHead>
              <TableHead>Görüntülenme</TableHead>
              <TableHead>Geçerlilik</TableHead>
              <TableHead />
            </TableRow>
          </TableHeader>
          <TableBody>
            {presentations.length === 0 && (
              <TableRow>
                <TableCell colSpan={6} className="text-muted-foreground text-center py-10">
                  Henüz sunum yok.
                </TableCell>
              </TableRow>
            )}
            {presentations.map((p) => (
              <TableRow key={p.$id}>
                <TableCell className="font-medium">{p.title}</TableCell>
                <TableCell>{customerName(p.customerId)}</TableCell>
                <TableCell>{propertyCount(p)} ilan</TableCell>
                <TableCell>{p.viewCount ?? 0}</TableCell>
                <TableCell className="text-muted-foreground">
                  {p.expiresAt ? new Date(p.expiresAt).toLocaleDateString("tr-TR") : "—"}
                </TableCell>
                <TableCell>
                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button variant="ghost" size="icon" className="size-8">
                        <DotsThree className="size-4" />
                      </Button>
                    </DropdownMenuTrigger>
                    <DropdownMenuContent align="end">
                      <DropdownMenuItem onClick={() => copyLink(p)}>
                        <Copy className="mr-2 size-4" />
                        Linki kopyala
                      </DropdownMenuItem>
                      <DropdownMenuItem asChild>
                        <a href={getShareUrl(p)} target="_blank" rel="noopener noreferrer">
                          <ArrowSquareOut className="mr-2 size-4" />
                          Önizleme
                        </a>
                      </DropdownMenuItem>
                      <DropdownMenuItem onClick={() => openEdit(p)}>
                        <PencilSimple className="mr-2 size-4" />
                        Düzenle
                      </DropdownMenuItem>
                      <DropdownMenuItem
                        onClick={() => setDeleteTarget(p)}
                        className="text-destructive focus:text-destructive"
                      >
                        <Trash className="mr-2 size-4" />
                        Sil
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <PresentationFormSheet
        open={sheetOpen}
        onOpenChange={setSheetOpen}
        presentation={editing}
        customers={customers}
        properties={properties}
        onSuccess={() => router.refresh()}
      />
      <DeleteConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(v) => { if (!v) setDeleteTarget(null); }}
        title={`"${deleteTarget?.title}" sunumu silinsin mi?`}
        description="Sunum ve paylaşım linki kalıcı olarak silinecek."
        onConfirm={doDelete}
      />
    </div>
  );
}
