"use client";

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

import Link from "next/link";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { deleteCustomerAction } from "@/lib/appwrite/customer-actions";
import { CustomerFormSheet } from "./customer-form-sheet";
import { CustomersPipeline } from "./customers-pipeline";
import { DeleteConfirmDialog } from "@/components/ui/delete-confirm-dialog";
import { UsageBadge } from "@/components/ui/usage-badge";
import type { Customer, CustomerType, CustomerStage } from "@/lib/appwrite/schema";
import {
  CUSTOMER_TYPE_LABELS,
  CUSTOMER_STAGE_LABELS,
  CUSTOMER_SOURCE_LABELS,
} from "@/lib/appwrite/schema";

type ViewMode = "list" | "pipeline";

interface CustomersClientProps {
  initialCustomers: Customer[];
  isOwner?: boolean;
  usageLimit?: { current: number; limit: number };
}

export function CustomersClient({ initialCustomers, isOwner, usageLimit }: CustomersClientProps) {
  const router = useRouter();
  const [customers, setCustomers] = useState(initialCustomers);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [editing, setEditing] = useState<Customer | null>(null);
  const [deleteTarget, setDeleteTarget] = useState<Customer | null>(null);
  const [viewMode, setViewMode] = useState<ViewMode>("list");
  const [typeFilter, setTypeFilter] = useState<CustomerType | "all">("all");
  const [stageFilter, setStageFilter] = useState<CustomerStage | "all">("all");

  const filteredCustomers = useMemo(() => {
    let list = customers;
    if (typeFilter !== "all") list = list.filter((c) => c.type === typeFilter);
    if (stageFilter !== "all") list = list.filter((c) => (c.stage ?? "ilk_temas") === stageFilter);
    return list;
  }, [customers, typeFilter, stageFilter]);

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

  function openCreate() { setEditing(null); setSheetOpen(true); }
  function openEdit(c: Customer) { setEditing(c); setSheetOpen(true); }

  async function doDelete() {
    if (!deleteTarget) return;
    const result = await deleteCustomerAction(deleteTarget.$id);
    if (result.ok) {
      setCustomers((prev) => prev.filter((x) => x.$id !== deleteTarget.$id));
      setDeleteTarget(null);
      toast.success("Müşteri silindi.");
    } else {
      toast.error(result.error ?? "Silinemedi.");
    }
  }

  return (
    <div className="flex flex-col gap-4 flex-1">
      {/* Header */}
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <h1 className="text-2xl font-bold">Müşteriler</h1>
        <div className="flex items-center gap-2 flex-wrap">
          {isOwner && usageLimit && (
            <UsageBadge current={usageLimit.current} limit={usageLimit.limit} label="müşteri" />
          )}
          {/* View toggle */}
          <div className="flex rounded-md border overflow-hidden">
            <button
              type="button"
              onClick={() => setViewMode("list")}
              className={`flex items-center gap-1.5 px-3 py-1.5 text-sm transition-colors ${
                viewMode === "list"
                  ? "bg-primary text-primary-foreground"
                  : "bg-background text-muted-foreground hover:text-foreground"
              }`}
            >
              <List className="size-3.5" />
              Liste
            </button>
            <button
              type="button"
              onClick={() => setViewMode("pipeline")}
              className={`flex items-center gap-1.5 px-3 py-1.5 text-sm transition-colors border-l ${
                viewMode === "pipeline"
                  ? "bg-primary text-primary-foreground"
                  : "bg-background text-muted-foreground hover:text-foreground"
              }`}
            >
              <Columns className="size-3.5" />
              Pipeline
            </button>
          </div>
          <Button onClick={openCreate} size="sm" data-tour="customers-add">
            <Plus className="mr-1.5 size-4" />
            Yeni Müşteri
          </Button>
        </div>
      </div>

      {/* Filter bar */}
      <div className="flex flex-wrap gap-2 items-center">
        <div className="flex gap-1">
          {([["all", "Tümü"], ["alici", "Alıcı"], ["kiraci", "Kiracı"], ["yatirimci", "Yatırımcı"]] as const).map(([key, label]) => {
            const count = key === "all" ? customers.length : customers.filter((c) => c.type === key).length;
            if (key !== "all" && count === 0) return null;
            return (
              <button key={key} type="button"
                onClick={() => setTypeFilter(key)}
                className={`px-3 py-1 text-xs rounded-full font-medium transition-colors ${
                  typeFilter === key ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:text-foreground"
                }`}
              >
                {label} <span className="opacity-70">{count}</span>
              </button>
            );
          })}
        </div>
        <div className="flex gap-1 ml-2 pl-2 border-l">
          {(["all", "ilk_temas", "aktif_arama", "teklif", "sozlesme", "kapandi"] as const).map((key) => {
            const label = key === "all" ? "Tüm aşamalar" : CUSTOMER_STAGE_LABELS[key];
            const count = key === "all" ? customers.length : customers.filter((c) => (c.stage ?? "ilk_temas") === key).length;
            if (key !== "all" && count === 0) return null;
            return (
              <button key={key} type="button"
                onClick={() => setStageFilter(key)}
                className={`px-3 py-1 text-xs rounded-full font-medium transition-colors ${
                  stageFilter === key ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:text-foreground"
                }`}
              >
                {label} <span className="opacity-70">{count}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Pipeline view */}
      {viewMode === "pipeline" && (
        <CustomersPipeline customers={filteredCustomers} onEdit={openEdit} />
      )}

      {/* List view */}
      {viewMode === "list" && (
        <div data-tour="customers-table" className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Ad Soyad</TableHead>
                <TableHead>Tip</TableHead>
                <TableHead>Aşama</TableHead>
                <TableHead>Telefon</TableHead>
                <TableHead>Kaynak</TableHead>
                <TableHead>Takip</TableHead>
                <TableHead />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredCustomers.length === 0 && (
                <TableRow>
                  <TableCell colSpan={7} className="text-muted-foreground text-center py-10">
                    {customers.length === 0 ? "Henüz müşteri yok." : "Filtreye uyan müşteri yok."}
                  </TableCell>
                </TableRow>
              )}
              {filteredCustomers.map((c) => (
                <TableRow key={c.$id}>
                  <TableCell className="font-medium">
                    <Link href={`/customers/${c.$id}`} className="hover:underline">
                      {c.name}
                    </Link>
                  </TableCell>
                  <TableCell>
                    <Badge variant="outline">
                      {CUSTOMER_TYPE_LABELS[c.type] ?? c.type}
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <StageBadge stage={c.stage} />
                  </TableCell>
                  <TableCell className="text-muted-foreground">{c.phone ?? "—"}</TableCell>
                  <TableCell className="text-muted-foreground">
                    {c.source ? (CUSTOMER_SOURCE_LABELS[c.source] ?? c.source) : "—"}
                  </TableCell>
                  <TableCell className="text-muted-foreground text-sm">
                    {c.nextFollowUpDate
                      ? new Date(c.nextFollowUpDate).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={() => openEdit(c)}>
                          <PencilSimple className="mr-2 size-4" />
                          Düzenle
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={() => setDeleteTarget(c)}
                          className="text-destructive focus:text-destructive"
                        >
                          <Trash className="mr-2 size-4" />
                          Sil
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

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

function StageBadge({ stage }: { stage?: string | null }) {
  const colors: Record<string, string> = {
    ilk_temas: "bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300",
    aktif_arama: "bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300",
    teklif: "bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300",
    sozlesme: "bg-purple-100 text-purple-700 dark:bg-purple-900/40 dark:text-purple-300",
    kapandi: "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300",
  };
  const key = stage ?? "ilk_temas";
  const label = CUSTOMER_STAGE_LABELS[key as keyof typeof CUSTOMER_STAGE_LABELS] ?? key;
  return (
    <span className={`inline-flex text-xs font-medium px-2 py-0.5 rounded-full ${colors[key] ?? colors.ilk_temas}`}>
      {label}
    </span>
  );
}
