"use client";
// src/app/customers/page.tsx
import { useState, useEffect, useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { ColumnDef } from "@tanstack/react-table";
import { AppShell } from "@/components/layout/AppShell";
import { DataTable } from "@/components/datatable/DataTable";
import { Button, PageHeader, Badge, ConfirmDialog } from "@/components/ui/index";
import { formatDate } from "@/lib/utils";
import { toast } from "sonner";
import { Plus, Eye, Pencil, Trash2, MoreHorizontal, Mail, Phone, Building2 } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { hasPermission } from "@/lib/permissions";
import { useLanguage } from "@/i18n/LanguageContext";

interface Customer {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  phone: string | null;
  jobTitle: string | null;
  city: string | null;
  country: string | null;
  deletedAt: string | null;
  createdAt: string;
  doNotEmail?: boolean;
  account: { id: string; name: string } | null;
  _count: { opportunities: number; activities: number; tickets: number };
}

export default function CustomersPage() {
  const router = useRouter();
  const { user } = useAuth();
  const { t } = useLanguage();
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [meta, setMeta] = useState({ total: 0, page: 1, pageSize: 10, pageCount: 1 });
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [sortBy, setSortBy] = useState("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);

  const canCreate = user && hasPermission(user.role, "customers:create");
  const canEdit = user && hasPermission(user.role, "customers:update");
  const canDelete = user && hasPermission(user.role, "customers:delete");

  const fetchCustomers = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({ page: String(page), pageSize: String(pageSize), sortBy, sortOrder, ...(search && { search }) });
      const res = await fetch(`/api/customers?${params}`);
      if (!res.ok) throw new Error("Failed to fetch");
      const data = await res.json();
      setCustomers(data.data.items);
      setMeta(data.data.meta);
    } catch {
      setError(t("customers.loadError"));
    } finally {
      setIsLoading(false);
    }
  }, [page, pageSize, sortBy, sortOrder, search, t]);

  useEffect(() => { fetchCustomers(); }, [fetchCustomers]);
  useEffect(() => { setPage(1); }, [search]);

  const handleDelete = async () => {
    if (!deleteId) return;
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/customers/${deleteId}`, { method: "DELETE" });
      if (!res.ok) throw new Error((await res.json()).error);
      toast.success(t("toast.customerDeactivated"));
      setDeleteId(null);
      fetchCustomers();
    } catch (e: any) { toast.error(e.message); }
    finally { setIsDeleting(false); }
  };

  const columns: ColumnDef<Customer, any>[] = useMemo(() => [
    {
      id: "name",
      header: t("table.colName"),
      accessorFn: (r) => `${r.firstName} ${r.lastName}`,
      cell: ({ row }) => {
        const c = row.original;
        return (
          <div>
            <Link href={`/customers/${c.id}`} className="font-medium text-primary hover:underline">
              {c.firstName} {c.lastName}
            </Link>
            {c.jobTitle && <div className="text-xs text-muted-foreground">{c.jobTitle}</div>}
          </div>
        );
      },
    },
    {
      id: "contact",
      header: t("table.colContact"),
      enableSorting: false,
      cell: ({ row }) => {
        const c = row.original;
        return (
          <div className="space-y-0.5">
            <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
              <Mail className="w-3 h-3" /><span className="truncate max-w-[160px]">{c.email}</span>
            </div>
            {c.phone && (
              <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
                <Phone className="w-3 h-3" />{c.phone}
              </div>
            )}
          </div>
        );
      },
    },
    {
      id: "company",
      header: t("table.colCompany"),
      enableSorting: false,
      cell: ({ row }) => row.original.account ? (
        <div className="flex items-center gap-1.5 text-sm">
          <Building2 className="w-3.5 h-3.5 text-muted-foreground" />
          <Link href={`/companies/${row.original.account.id}`} className="text-primary hover:underline">
            {row.original.account.name}
          </Link>
        </div>
      ) : <span className="text-muted-foreground text-sm">—</span>,
    },
    {
      id: "location",
      header: t("table.colLocation"),
      enableSorting: false,
      cell: ({ row }) => {
        const c = row.original;
        const loc = [c.city, c.country].filter(Boolean).join(", ");
        return <span className="text-sm text-muted-foreground">{loc || "—"}</span>;
      },
    },
    {
      id: "activity",
      header: t("table.colActivity"),
      enableSorting: false,
      cell: ({ row }) => {
        const c = row.original._count;
        return (
          <div className="flex gap-2 text-xs text-muted-foreground">
            <span>{c.opportunities} {t("table.colDeals")}</span>
            <span>·</span>
            <span>{c.tickets} {t("table.colTicketsShort")}</span>
          </div>
        );
      },
    },
    {
      id: "status",
      header: t("common.status"),
      enableSorting: false,
      cell: ({ row }) => (
        <Badge variant={!row.original.deletedAt ? "success" : "secondary"}>
          {row.original.doNotEmail ? t("table.statusDoNotEmail") : t("table.statusActive")}
        </Badge>
      ),
    },
    {
      accessorKey: "createdAt",
      header: t("table.colCreated"),
      cell: ({ getValue }) => <span className="text-xs text-muted-foreground">{formatDate(getValue() as string)}</span>,
    },
    {
      id: "actions",
      header: "",
      enableSorting: false,
      size: 48,
      cell: ({ row }) => {
        const c = row.original;
        const isOpen = openMenuId === c.id;
        return (
          <div className="relative flex justify-end">
            <button onClick={(e) => { e.stopPropagation(); setOpenMenuId(isOpen ? null : c.id); }}
              className="p-1.5 rounded-lg hover:bg-accent text-muted-foreground hover:text-foreground transition-colors">
              <MoreHorizontal className="w-4 h-4" />
            </button>
            {isOpen && (
              <>
                <div className="fixed inset-0 z-10" onClick={() => setOpenMenuId(null)} />
                <div className="absolute top-full end-0 mt-1 bg-popover border border-border rounded-lg shadow-lg py-1 z-50 min-w-[140px] animate-fade-in">
                  <Link href={`/customers/${c.id}`} onClick={() => setOpenMenuId(null)}
                    className="flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors">
                    <Eye className="w-4 h-4" /> {t("common.view")}
                  </Link>
                  {canEdit && (
                    <Link href={`/customers/${c.id}/edit`} onClick={() => setOpenMenuId(null)}
                      className="flex items-center gap-2 px-3 py-1.5 text-sm hover:bg-accent transition-colors">
                      <Pencil className="w-4 h-4" /> {t("common.edit")}
                    </Link>
                  )}
                  {canDelete && (
                    <button onClick={() => { setOpenMenuId(null); setDeleteId(c.id); }}
                      className="flex items-center gap-2 px-3 py-1.5 text-sm text-destructive hover:bg-accent w-full transition-colors">
                      <Trash2 className="w-4 h-4" /> {t("table.deactivate")}
                    </button>
                  )}
                </div>
              </>
            )}
          </div>
        );
      },
    },
  ], [t, canEdit, canDelete, openMenuId]);

  return (
    <AppShell breadcrumbs={[{ label: t("nav.customers") }]}>
      <PageHeader
        title={`${t("contacts.title")}${!isLoading ? ` (${meta.total})` : ""}`}
        description={t("customers.listSubtitle")}
      >
        {canCreate && (
          <Button onClick={() => router.push("/customers/new")}>
            <Plus className="w-4 h-4" /> {t("contacts.new")}
          </Button>
        )}
      </PageHeader>
      <DataTable
        data={customers} columns={columns} isLoading={isLoading} error={error}
        getRowClassName={(r) => (openMenuId === r.id ? "relative z-50" : undefined)}
        pageCount={meta.pageCount} page={meta.page} pageSize={meta.pageSize} total={meta.total}
        onPageChange={setPage} onPageSizeChange={(s) => { setPageSize(s); setPage(1); }}
        searchValue={search} onSearchChange={setSearch}
        searchPlaceholder={t("customers.searchPlaceholder")}
        sortBy={sortBy} sortOrder={sortOrder}
        onSortChange={(by, order) => { setSortBy(by); setSortOrder(order); }}
        onBulkDelete={canDelete ? async (ids) => {
          await Promise.all(ids.map(id => fetch(`/api/customers/${id}`, { method: "DELETE" })));
          toast.success(t("toast.customersBulkDeactivated", { count: ids.length })); fetchCustomers();
        } : undefined}
        getRowId={(r) => r.id}
        emptyTitle={t("customers.emptyListTitle")}
        emptyDescription={t("customers.emptyListDescription")}
        emptyAction={canCreate ? <Button onClick={() => router.push("/customers/new")} size="sm"><Plus className="w-4 h-4" /> {t("contacts.new")}</Button> : undefined}
      />
      <ConfirmDialog open={!!deleteId} onClose={() => setDeleteId(null)} onConfirm={handleDelete}
        isLoading={isDeleting} title={t("customers.dialogDeactivateTitle")}
        description={t("customers.dialogDeactivateDesc")}
        confirmLabel={t("table.deactivate")} variant="destructive" />
    </AppShell>
  );
}
