"use client";
// src/app/leads/[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, Badge } from "@/components/ui/index";
import { formatDate, formatCurrency, formatRelativeTime, LEAD_SOURCE_LABELS, LEAD_SOURCE_LABELS_AR, LEAD_STATUS_COLORS, ACTIVITY_TYPE_ICONS } from "@/lib/utils";
import { useLanguage } from "@/i18n/LanguageContext";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";
import { hasPermission } from "@/lib/permissions";
import type { LeadStatus } from "@prisma/client";
import {
  Pencil, Trash2, Mail, Phone, Globe, MapPin, Building2,
  Briefcase, Calendar, Activity, CheckSquare, UserCheck,
  ArrowRightLeft, Loader2, AlertCircle, TrendingUp,
} from "lucide-react";
import { EntityCustomFieldsReadOnly } from "@/components/custom-fields/EntityCustomFieldsSection";

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

  const [lead, setLead] = 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, "leads:update");
  const canDelete = user && hasPermission(user.role, "leads:delete");

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

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/leads/${id}`, { method: "DELETE" });
      if (!res.ok) throw new Error((await res.json()).error ?? "Delete failed");
      toast.success(ar ? "تم حذف العميل المحتمل" : "Lead deleted");
      router.push("/leads");
    } catch (e: any) {
      toast.error(e.message);
    } finally {
      setIsDeleting(false);
    }
  };

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

  if (error || !lead) return (
    <AppShell breadcrumbs={[{ label: ar ? "العملاء المحتملون" : "Leads", href: "/leads" }, { 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("/leads")}>
          {ar ? "رجوع" : "Back"}
        </Button>
      </div>
    </AppShell>
  );

  const sourceLabels = ar ? LEAD_SOURCE_LABELS_AR : LEAD_SOURCE_LABELS;
  const st = lead.status as LeadStatus;
  const statusClass =
    LEAD_STATUS_COLORS[st] ?? "bg-gray-100 text-gray-600";
  const STATUS_LABEL_AR: Record<LeadStatus, string> = {
    NEW: "جديد",
    CONTACTED: "تم التواصل",
    QUALIFIED: "مؤهل",
    UNQUALIFIED: "غير مؤهل",
    CONVERTED: "محوّل",
    LOST: "مفقود",
  };
  const STATUS_LABEL_EN: Record<LeadStatus, string> = {
    NEW: "New",
    CONTACTED: "Contacted",
    QUALIFIED: "Qualified",
    UNQUALIFIED: "Unqualified",
    CONVERTED: "Converted",
    LOST: "Lost",
  };
  const statusLabel = ar ? STATUS_LABEL_AR[st] : STATUS_LABEL_EN[st];

  return (
    <AppShell breadcrumbs={[
      { label: ar ? "العملاء المحتملون" : "Leads", href: "/leads" },
      { label: `${lead.firstName} ${lead.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-primary/10 flex items-center justify-center text-primary font-bold text-lg flex-shrink-0">
            {lead.firstName[0]}{lead.lastName[0]}
          </div>
          <div>
            <div className="flex items-center gap-3 flex-wrap">
              <h1 className="text-xl font-bold text-foreground">
                {lead.firstName} {lead.lastName}
              </h1>
              <span className={`text-xs px-2.5 py-0.5 rounded-full font-medium ${statusClass}`}>
                {statusLabel}
              </span>
              {lead.isConverted && (
                <Badge variant="success">{ar ? "محوّل" : "Converted"}</Badge>
              )}
            </div>
            {(lead.jobTitle || lead.company) && (
              <p className="text-sm text-muted-foreground mt-0.5">
                {[lead.jobTitle, lead.company].filter(Boolean).join(ar ? " في " : " at ")}
              </p>
            )}
          </div>
        </div>
        <div className="flex items-center gap-2">
          {lead.contact && (
            <Link href={`/customers/${lead.contact.id}`}>
              <Button variant="outline" size="sm">
                <UserCheck className="w-4 h-4" />
                {ar ? "عرض العميل" : "View Customer"}
              </Button>
            </Link>
          )}
          {!lead.isConverted && canEdit && (
            <Link href={`/leads/${lead.id}/convert`}>
              <Button variant="secondary" size="sm">
                <ArrowRightLeft className="w-4 h-4" />
                {ar ? "تحويل إلى عميل" : "Convert to Customer"}
              </Button>
            </Link>
          )}
          {canEdit && (
            <Link href={`/leads/${lead.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">
        {/* Left */}
        <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: lead.email ? <a href={`mailto:${lead.email}`} className="text-primary hover:underline text-sm">{lead.email}</a> : "—" },
                { icon: <Phone className="w-4 h-4" />, label: ar ? "الهاتف" : "Phone",
                  value: lead.phone ? <a href={`tel:${lead.phone}`} className="text-primary hover:underline text-sm">{lead.phone}</a> : "—" },
                { icon: <Building2 className="w-4 h-4" />, label: ar ? "الشركة" : "Company",
                  value: lead.company ?? "—" },
                { icon: <Briefcase className="w-4 h-4" />, label: ar ? "المسمى الوظيفي" : "Job Title",
                  value: lead.jobTitle ?? "—" },
                { icon: <Globe className="w-4 h-4" />, label: ar ? "الموقع" : "Website",
                  value: lead.website
                    ? <a href={lead.website} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline text-sm truncate">{lead.website}</a>
                    : "—" },
                { icon: <MapPin className="w-4 h-4" />, label: ar ? "الموقع الجغرافي" : "Location",
                  value: [lead.city, lead.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 flex-shrink-0">{icon}</span>
                  <div>
                    <p className="text-xs text-muted-foreground font-medium">{label}</p>
                    <div className="text-sm text-foreground mt-0.5 break-words">{value}</div>
                  </div>
                </div>
              ))}
              <EntityCustomFieldsReadOnly
                embed
                definitions={lead.customFieldData?.definitions ?? []}
                values={lead.customFieldData?.values ?? {}}
              />
            </CardContent>
          </Card>

          {/* Notes */}
          {lead.notes && (
            <Card>
              <CardHeader><CardTitle>{ar ? "ملاحظات" : "Notes"}</CardTitle></CardHeader>
              <CardContent>
                <p className="text-sm text-foreground whitespace-pre-wrap leading-relaxed">{lead.notes}</p>
              </CardContent>
            </Card>
          )}

          {/* Activities */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{ar ? `الأنشطة (${lead.activities?.length ?? 0})` : `Activities (${lead.activities?.length ?? 0})`}</CardTitle>
              <Link href={`/activities/new?leadId=${lead.id}`}>
                <Button variant="outline" size="sm">
                  {ar ? "تسجيل نشاط" : "Log Activity"}
                </Button>
              </Link>
            </CardHeader>
            <CardContent className="p-0">
              {!lead.activities?.length ? (
                <div className="py-8 text-center text-muted-foreground text-sm">
                  {ar ? "لا توجد أنشطة بعد" : "No activities yet"}
                </div>
              ) : (
                <div className="divide-y divide-border">
                  {lead.activities.map((a: any) => (
                    <div key={a.id} className="px-6 py-3 flex items-start gap-3">
                      <span className="text-lg mt-0.5">{ACTIVITY_TYPE_ICONS[a.type] ?? "📌"}</span>
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between gap-2">
                          <p className="text-sm font-medium text-foreground truncate">{a.subject}</p>
                          <span className="text-xs text-muted-foreground flex-shrink-0">{formatRelativeTime(a.createdAt, language)}</span>
                        </div>
                        {a.description && <p className="text-xs text-muted-foreground mt-0.5 line-clamp-1">{a.description}</p>}
                        <p className="text-xs text-muted-foreground mt-1">{ar ? "بواسطة" : "by"} {a.user.name}</p>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Tasks */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{ar ? `المهام (${lead.tasks?.length ?? 0})` : `Tasks (${lead.tasks?.length ?? 0})`}</CardTitle>
              <Link href={`/tasks/new?leadId=${lead.id}`}>
                <Button variant="outline" size="sm">{ar ? "إضافة مهمة" : "Add Task"}</Button>
              </Link>
            </CardHeader>
            <CardContent className="p-0">
              {!lead.tasks?.length ? (
                <div className="py-8 text-center text-muted-foreground text-sm">
                  {ar ? "لا توجد مهام" : "No tasks yet"}
                </div>
              ) : (
                <div className="divide-y divide-border">
                  {lead.tasks.map((t: any) => (
                    <Link key={t.id} href={`/tasks/${t.id}`} className="px-6 py-3 flex items-center gap-3 hover:bg-muted/40 transition-colors">
                      <CheckSquare className={`w-4 h-4 flex-shrink-0 ${t.status === "DONE" ? "text-green-500" : "text-muted-foreground"}`} />
                      <div className="flex-1 min-w-0">
                        <p className={`text-sm font-medium ${t.status === "DONE" ? "line-through text-muted-foreground" : "text-foreground"}`}>{t.title}</p>
                        {t.dueDate && <p className="text-xs text-muted-foreground">{formatDate(t.dueDate)}</p>}
                      </div>
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium capitalize
                        ${t.priority === "URGENT" ? "bg-red-100 text-red-700" : t.priority === "HIGH" ? "bg-orange-100 text-orange-700" : t.priority === "MEDIUM" ? "bg-blue-100 text-blue-700" : "bg-gray-100 text-gray-600"}`}>
                        {t.priority.toLowerCase()}
                      </span>
                    </Link>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Right sidebar */}
        <div className="space-y-6">
          <Card>
            <CardHeader><CardTitle>{ar ? "تفاصيل العميل" : "Lead Details"}</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              <div>
                <p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-1">{ar ? "المصدر" : "Source"}</p>
                <p className="text-sm font-medium">{sourceLabels[lead.source] ?? lead.source}</p>
              </div>
              <div>
                <p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-1">{ar ? "درجة العميل" : "Lead Score"}</p>
                <div className="flex items-center gap-2">
                  <div className="flex-1 h-2 bg-muted rounded-full overflow-hidden">
                    <div className={`h-full rounded-full ${lead.score >= 70 ? "bg-green-500" : lead.score >= 40 ? "bg-amber-500" : "bg-red-500"}`}
                      style={{ width: `${lead.score}%` }} />
                  </div>
                  <span className="text-sm font-bold">{lead.score}/100</span>
                </div>
              </div>
              {lead.budget && (
                <div>
                  <p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-1">{ar ? "الميزانية" : "Budget"}</p>
                  <p className="text-sm font-medium">{formatCurrency(lead.budget, lead.currency)}</p>
                </div>
              )}
              {lead.industry && (
                <div>
                  <p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-1">{ar ? "القطاع" : "Industry"}</p>
                  <p className="text-sm font-medium">{lead.industry}</p>
                </div>
              )}
              <div>
                <p className="text-xs text-muted-foreground uppercase tracking-wide font-medium mb-1">{ar ? "مُسند إلى" : "Assigned To"}</p>
                <p className="text-sm font-medium">{lead.assignedTo?.name ?? (ar ? "غير مُسند" : "Unassigned")}</p>
              </div>
              <div className="pt-2 border-t border-border space-y-2 text-xs text-muted-foreground">
                <div className="flex justify-between">
                  <span>{ar ? "تاريخ الإنشاء" : "Created"}</span>
                  <span>{formatDate(lead.createdAt)}</span>
                </div>
                <div className="flex justify-between">
                  <span>{ar ? "آخر تحديث" : "Updated"}</span>
                  <span>{formatRelativeTime(lead.updatedAt, language)}</span>
                </div>
                {lead.createdBy && (
                  <div className="flex justify-between">
                    <span>{ar ? "أنشأه" : "Created by"}</span>
                    <span>{lead.createdBy.name}</span>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

        </div>
      </div>

      <ConfirmDialog
        open={deleteOpen}
        onClose={() => setDeleteOpen(false)}
        onConfirm={handleDelete}
        isLoading={isDeleting}
        title={ar ? "حذف العميل المحتمل" : "Delete Lead"}
        description={ar ? `هل أنت متأكد من حذف ${lead.firstName} ${lead.lastName}؟` : `Delete ${lead.firstName} ${lead.lastName} permanently?`}
        confirmLabel={ar ? "حذف" : "Delete"}
        variant="destructive"
      />
    </AppShell>
  );
}
