"use client";
// src/app/customers/[id]/page.tsx
import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import { AppShell } from "@/components/layout/AppShell";
import { Button, Card, CardHeader, CardTitle, CardContent, ConfirmDialog } from "@/components/ui/index";
import { formatDate, formatCurrency, formatRelativeTime, OPP_STAGE_COLORS, OPP_STAGE_LABELS, OPP_STAGE_LABELS_AR } from "@/lib/utils";
import { useLanguage } from "@/i18n/LanguageContext";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";
import { hasPermission } from "@/lib/permissions";
import { Pencil, Trash2, Mail, Phone, MapPin, Building2, Briefcase, Loader2, AlertCircle, Plus } from "lucide-react";
import { EntityCustomFieldsReadOnly } from "@/components/custom-fields/EntityCustomFieldsSection";

export default function ContactDetailPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const { user } = useAuth();
  const { language } = useLanguage();
  const ar = language === "ar";

  const [contact, setContact] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deleteOpen, setDeleteOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);

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

  useEffect(() => {
    fetch(`/api/customers/${id}`)
      .then(r => { if (!r.ok) throw new Error("Not found"); return r.json(); })
      .then(d => setContact(d.data))
      .catch(e => setError(e.message))
      .finally(() => setIsLoading(false));
  }, [id]);

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      await fetch(`/api/customers/${id}`, { method: "DELETE" });
      toast.success(ar ? "تم حذف العميل" : "Customer deleted");
      router.push("/customers");
    } catch {
      toast.error(ar ? "فشل الحذف" : "Delete failed");
    } finally {
      setIsDeleting(false);
    }
  };

  if (isLoading) return (
    <AppShell breadcrumbs={[{ label: ar ? "العملاء" : "Customers", href: "/customers" }, { label: "..." }]}>
      <div className="flex justify-center h-64 items-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div>
    </AppShell>
  );

  if (error || !contact) return (
    <AppShell breadcrumbs={[{ label: ar ? "العملاء" : "Customers", href: "/customers" }, { label: "404" }]}>
      <div className="flex flex-col items-center justify-center h-64 gap-4">
        <AlertCircle className="w-12 h-12 text-destructive" />
        <p className="text-lg font-semibold">{error ?? "Not found"}</p>
        <Button variant="outline" onClick={() => router.push("/customers")}>{ar ? "رجوع" : "Back"}</Button>
      </div>
    </AppShell>
  );

  const stageLabels = ar ? OPP_STAGE_LABELS_AR : OPP_STAGE_LABELS;

  return (
    <AppShell breadcrumbs={[
      { label: ar ? "العملاء" : "Customers", href: "/customers" },
      { label: `${contact.firstName} ${contact.lastName}` },
    ]}>
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-6">
        <div className="flex items-start gap-4">
          <div className="w-12 h-12 rounded-xl bg-green-100 flex items-center justify-center text-green-700 font-bold text-lg">
            {contact.firstName[0]}{contact.lastName[0]}
          </div>
          <div>
            <h1 className="text-xl font-bold text-foreground">{contact.firstName} {contact.lastName}</h1>
            {(contact.jobTitle || contact.account) && (
              <p className="text-sm text-muted-foreground mt-0.5">
                {contact.jobTitle}
                {contact.jobTitle && contact.account ? (ar ? " في " : " at ") : ""}
                {contact.account?.name}
              </p>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2">
          {canEdit && <Link href={`/customers/${id}/edit`}><Button variant="outline" size="sm"><Pencil className="w-4 h-4" /> {ar ? "تعديل" : "Edit"}</Button></Link>}
          {canDelete && <Button variant="destructive" size="sm" onClick={() => setDeleteOpen(true)}><Trash2 className="w-4 h-4" /></Button>}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          {/* Customer Info */}
          <Card>
            <CardHeader><CardTitle>{ar ? "معلومات العميل" : "Customer Information"}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {[
                { icon: <Mail className="w-4 h-4"/>, label: ar ? "البريد" : "Email",
                  value: <a href={`mailto:${contact.email}`} className="text-primary hover:underline text-sm">{contact.email}</a> },
                { icon: <Phone className="w-4 h-4"/>, label: ar ? "الهاتف" : "Phone",
                  value: contact.phone ? <a href={`tel:${contact.phone}`} className="text-primary hover:underline text-sm">{contact.phone}</a> : "—" },
                { icon: <Briefcase className="w-4 h-4"/>, label: ar ? "المسمى" : "Job Title", value: contact.jobTitle ?? "—" },
                { icon: <Building2 className="w-4 h-4"/>, label: ar ? "الحساب" : "Account",
                  value: contact.account
                    ? <Link href={`/companies/${contact.account.id}`} className="text-primary hover:underline">{contact.account.name}</Link>
                    : "—" },
                { icon: <MapPin className="w-4 h-4"/>, label: ar ? "الموقع" : "Location",
                  value: [contact.city, contact.country].filter(Boolean).join(", ") || "—" },
              ].map(({ icon, label, value }) => (
                <div key={label} className="flex items-start gap-3">
                  <span className="text-muted-foreground mt-0.5">{icon}</span>
                  <div>
                    <p className="text-xs text-muted-foreground font-medium">{label}</p>
                    <div className="text-sm text-foreground mt-0.5">{value}</div>
                  </div>
                </div>
              ))}
              <EntityCustomFieldsReadOnly
                embed
                definitions={contact.customFieldData?.definitions ?? []}
                values={contact.customFieldData?.values ?? {}}
              />
            </CardContent>
          </Card>

          {/* Opportunities */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{ar ? `الصفقات (${contact.opportunities?.length ?? 0})` : `Opportunities (${contact.opportunities?.length ?? 0})`}</CardTitle>
              <Link href={`/deals/new?contactId=${id}`}>
                <Button variant="outline" size="sm"><Plus className="w-4 h-4" /> {ar ? "جديد" : "New"}</Button>
              </Link>
            </CardHeader>
            <CardContent className="p-0">
              {!contact.opportunities?.length ? (
                <div className="py-8 text-center text-muted-foreground text-sm">{ar ? "لا توجد صفقات" : "No opportunities yet"}</div>
              ) : (
                <div className="divide-y divide-border">
                  {contact.opportunities.map((o: any) => (
                    <div key={o.id} className="px-6 py-3 flex items-center justify-between gap-4">
                      <div>
                        <Link href={`/deals/${o.id}`} className="text-sm font-medium text-primary hover:underline">{o.title}</Link>
                        <p className="text-xs text-muted-foreground">{o.assignedTo?.name ?? (ar ? "غير مُسند" : "Unassigned")}</p>
                      </div>
                      <div className="flex items-center gap-3">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${OPP_STAGE_COLORS[o.stage] ?? "bg-gray-100"}`}>
                          {stageLabels[o.stage] ?? o.stage}
                        </span>
                        <span className="text-sm font-semibold">{formatCurrency(o.value, o.currency)}</span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Activities */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{ar ? "الأنشطة الأخيرة" : "Recent Activities"}</CardTitle>
              <Link href={`/activities/new?contactId=${id}`}>
                <Button variant="outline" size="sm">{ar ? "تسجيل نشاط" : "Log Activity"}</Button>
              </Link>
            </CardHeader>
            <CardContent className="p-0">
              {!contact.activities?.length ? (
                <div className="py-8 text-center text-muted-foreground text-sm">{ar ? "لا توجد أنشطة" : "No activities yet"}</div>
              ) : (
                <div className="divide-y divide-border">
                  {contact.activities.slice(0, 5).map((a: any) => (
                    <div key={a.id} className="px-6 py-3">
                      <div className="flex items-center justify-between">
                        <p className="text-sm font-medium">{a.subject}</p>
                        <span className="text-xs text-muted-foreground">{formatRelativeTime(a.createdAt, language)}</span>
                      </div>
                      <p className="text-xs text-muted-foreground mt-0.5">{ar ? "بواسطة" : "by"} {a.user?.name}</p>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          <Card>
            <CardHeader><CardTitle>{ar ? "ملخص" : "Summary"}</CardTitle></CardHeader>
            <CardContent className="space-y-3">
              {[
                { label: ar ? "إجمالي الصفقات" : "Opportunities", value: contact._count?.opportunities ?? 0 },
                { label: ar ? "التذاكر المفتوحة" : "Tickets",      value: contact._count?.tickets ?? 0 },
                { label: ar ? "الأنشطة" : "Activities",            value: contact._count?.activities ?? 0 },
              ].map(({ label, value }) => (
                <div key={label} className="flex justify-between items-center">
                  <span className="text-sm text-muted-foreground">{label}</span>
                  <span className="text-sm font-bold text-foreground">{value}</span>
                </div>
              ))}
              <div className="pt-2 border-t border-border">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">{ar ? "تاريخ الإضافة" : "Added"}</span>
                  <span>{formatDate(contact.createdAt)}</span>
                </div>
              </div>
            </CardContent>
          </Card>

          {contact.lead && (
            <Card>
              <CardHeader><CardTitle>{ar ? "محوّل من" : "Converted From"}</CardTitle></CardHeader>
              <CardContent>
                <Link href={`/leads/${contact.lead.id}`} className="text-sm text-primary hover:underline">
                  {ar ? "عرض العميل المحتمل الأصلي ←" : "View Original Lead →"}
                </Link>
              </CardContent>
            </Card>
          )}

          {contact.doNotEmail && (
            <div className="px-4 py-3 bg-amber-50 border border-amber-200 rounded-xl text-sm text-amber-700">
              ⛔ {ar ? "عدم إرسال بريد تسويقي" : "Do Not Email"}
            </div>
          )}
          {contact.doNotCall && (
            <div className="px-4 py-3 bg-amber-50 border border-amber-200 rounded-xl text-sm text-amber-700">
              ⛔ {ar ? "عدم الاتصال الهاتفي" : "Do Not Call"}
            </div>
          )}
        </div>
      </div>

      <ConfirmDialog
        open={deleteOpen} onClose={() => setDeleteOpen(false)} onConfirm={handleDelete}
        isLoading={isDeleting}
        title={ar ? "حذف العميل" : "Delete Customer"}
        description={ar ? "سيتم حذف العميل. البيانات المرتبطة ستُحفظ." : "Customer will be deleted. Related data is preserved."}
        confirmLabel={ar ? "حذف" : "Delete"}
        variant="destructive"
      />
    </AppShell>
  );
}
