"use client";
// src/app/deals/[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, getLabel, DEAL_STAGE_LABELS, DEAL_STAGE_LABELS_AR } from "@/lib/utils";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";
import { hasPermission } from "@/lib/permissions";
import { Pencil, Trash2, Loader2, AlertCircle } from "lucide-react";
import { useLanguage } from "@/i18n/LanguageContext";
import { EntityCustomFieldsReadOnly } from "@/components/custom-fields/EntityCustomFieldsSection";

const STAGE_COLORS: Record<string, string> = {
   QUALIFICATION: "bg-violet-100 text-violet-700",
  PROPOSAL: "bg-amber-100 text-amber-700", NEGOTIATION: "bg-orange-100 text-orange-700",
  CLOSED_WON: "bg-green-100 text-green-700", CLOSED_LOST: "bg-red-100 text-red-700",
};

export default function DealDetailPage() {
  const { id } = useParams() as { id: string };
  const router = useRouter();
  const { user } = useAuth();
  const { t, language } = useLanguage();
  const [deal, setDeal] = 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, "deals:update");
  const canDelete = user && hasPermission(user.role, "deals:delete");

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

  const handleDelete = async () => {
    setIsDeleting(true);
    try {
      await fetch(`/api/deals/${id}`, { method: "DELETE" });
      toast.success(t("deals.toastArchivedOk"));
      router.push("/deals");
    } catch { toast.error(t("deals.loadError")); }
    finally { setIsDeleting(false); }
  };

  if (isLoading) return <AppShell breadcrumbs={[{ label: t("deals.title"), href: "/deals" }, { label: t("common.breadcrumbLoading") }]}><div className="flex justify-center h-64 items-center"><Loader2 className="w-8 h-8 animate-spin text-primary" /></div></AppShell>;
  if (error || !deal) return <AppShell breadcrumbs={[{ label: t("deals.title"), href: "/deals" }, { label: t("common.breadcrumbNotFound") }]}><div className="flex flex-col items-center justify-center h-64 gap-4"><AlertCircle className="w-12 h-12 text-destructive" /><p>{error ?? t("error.notFound")}</p><Button variant="outline" onClick={() => router.push("/deals")}>{t("common.back")}</Button></div></AppShell>;

  return (
    <AppShell breadcrumbs={[{ label: t("deals.title"), href: "/deals" }, { label: deal.title }]}>
      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-6">
        <div>
          <div className="flex items-center gap-3 flex-wrap">
            <h1 className="text-xl font-bold text-foreground">{deal.title}</h1>
            <span className={`text-xs px-2.5 py-1 rounded-full font-medium ${STAGE_COLORS[deal.stage] ?? "bg-gray-100 text-gray-600"}`}>{getLabel(DEAL_STAGE_LABELS, DEAL_STAGE_LABELS_AR, deal.stage, language)}</span>
          </div>
          <p className="text-2xl font-bold text-primary mt-2">{formatCurrency(deal.value, deal.currency)}</p>
        </div>
        <div className="flex items-center gap-2">
          {canEdit && <Link href={`/deals/${id}/edit`}><Button variant="outline" size="sm"><Pencil className="w-4 h-4" /> {t("common.edit")}</Button></Link>}
          {canDelete && <Button variant="destructive" size="sm" onClick={() => setDeleteOpen(true)}><Trash2 className="w-4 h-4" /> {t("deals.archive")}</Button>}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          {/* Pipeline progress */}
          <Card>
            <CardHeader><CardTitle>{t("deals.detailPipeline")}</CardTitle></CardHeader>
            <CardContent>
              <div className="flex items-center gap-1">
                {["QUALIFICATION", "DISCOVERY", "PROPOSAL", "NEGOTIATION", "CONTRACT"].map((s, i) => {
                  const stages = ["QUALIFICATION", "DISCOVERY", "PROPOSAL", "NEGOTIATION", "CONTRACT"];
                  const currentIdx = stages.indexOf(deal.stage);
                  const isActive = stages.indexOf(s) <= currentIdx;
                  const isCurrent = s === deal.stage;
                  return (
                    <div key={s} className="flex-1 flex flex-col items-center gap-1">
                      <div className={`w-full h-2 rounded-full transition-all ${isActive ? "bg-primary" : "bg-muted"}`} />
                      <span className={`text-xs text-center hidden sm:block ${isCurrent ? "font-bold text-primary" : "text-muted-foreground"}`}>
                        {getLabel(DEAL_STAGE_LABELS, DEAL_STAGE_LABELS_AR, s, language)}
                      </span>
                    </div>
                  );
                })}
              </div>
              <div className="flex items-center gap-2 mt-3">
                <div className="w-24 h-1.5 bg-muted rounded-full overflow-hidden">
                  <div className="h-full bg-primary rounded-full" style={{ width: `${deal.probability}%` }} />
                </div>
                <span className="text-sm text-muted-foreground">{deal.probability}% {t("deals.probClosePct")}</span>
              </div>
            </CardContent>
          </Card>

          {/* Recent activities */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{t("deals.cardActivities")} ({deal.activities?.length ?? 0})</CardTitle>
              <Link href={`/activities/new?opportunityId=${id}`}>
                <Button variant="outline" size="sm">
                  {t("activities.logActivity")}
                </Button>
              </Link>
            </CardHeader>
            <CardContent className="p-0">
              {deal.activities?.length === 0 ? (
                <div className="py-8 text-center text-muted-foreground text-sm">{t("deals.emptyActivities")}</div>
              ) : (
                <div className="divide-y divide-border">
                  {deal.activities?.map((a: any) => (
                    <div key={a.id} className="px-6 py-3">
                      <div className="flex justify-between">
                        <p className="text-sm font-medium">{a.subject}</p>
                        <span className="text-xs text-muted-foreground">{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-0.5">{t("deals.activityBy")} {a.user?.name}</p>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        <div className="space-y-6">
          <Card>
            <CardHeader><CardTitle>{t("deals.detailCard")}</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              {deal.customer && (
                <div>
                  <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("deals.labelCustomer")}</p>
                  <Link href={`/customers/${deal.customer.id}`} className="text-sm text-primary hover:underline font-medium">
                    {deal.customer.firstName} {deal.customer.lastName}
                  </Link>
                </div>
              )}
              {deal.company && (
                <div>
                  <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("deals.labelCompany")}</p>
                  <Link href={`/companies/${deal.company.id}`} className="text-sm text-primary hover:underline font-medium">{deal.company.name}</Link>
                </div>
              )}
              <div>
                <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("deals.labelAssignedTo")}</p>
                <p className="text-sm font-medium">{deal.assignedTo?.name ?? t("deals.unassigned")}</p>
              </div>
              {deal.closeDate && (
                <div>
                  <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("deals.labelExpectedClose")}</p>
                  <p className="text-sm font-medium">{formatDate(deal.closeDate, language)}</p>
                </div>
              )}
              <div className="pt-2 border-t border-border">
                <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("deals.labelCreated")}</p>
                <p className="text-sm">{formatDate(deal.createdAt, language)}</p>
              </div>
              <EntityCustomFieldsReadOnly
                embed
                definitions={deal.customFieldData?.definitions ?? []}
                values={deal.customFieldData?.values ?? {}}
              />
            </CardContent>
          </Card>
          {deal.notes && (
            <Card>
              <CardHeader><CardTitle>{t("deals.cardNotes")}</CardTitle></CardHeader>
              <CardContent><p className="text-sm whitespace-pre-wrap">{deal.notes}</p></CardContent>
            </Card>
          )}
        </div>
      </div>

      <ConfirmDialog open={deleteOpen} onClose={() => setDeleteOpen(false)} onConfirm={handleDelete}
        isLoading={isDeleting} title={t("deals.archiveTitle")} description={t("deals.archiveDesc")}
        confirmLabel={t("deals.archive")} variant="destructive" />
    </AppShell>
  );
}
