"use client";
// src/app/companies/[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, Globe, Phone, Mail, MapPin, Loader2, AlertCircle, Plus } from "lucide-react";
import { useLanguage } from "@/i18n/LanguageContext";
import { EntityCustomFieldsReadOnly } from "@/components/custom-fields/EntityCustomFieldsSection";

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

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

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

  if (isLoading) return <AppShell breadcrumbs={[{ label: t("companies.title"), href: "/companies" }, { 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 || !company) return <AppShell breadcrumbs={[{ label: t("companies.title"), href: "/companies" }, { 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("/companies")}>{t("common.back")}</Button></div></AppShell>;

  return (
    <AppShell breadcrumbs={[{ label: t("companies.title"), href: "/companies" }, { label: company.name }]}>
      <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-blue-100 flex items-center justify-center text-blue-700 font-bold text-lg">
            {company.name[0]}
          </div>
          <div>
            <h1 className="text-xl font-bold text-foreground">{company.name}</h1>
            <p className="text-sm text-muted-foreground mt-0.5">
              {[company.industry, company.size ? t("companies.employeesFmt", { n: company.size }) : null].filter(Boolean).join(" · ") || t("companies.subtitleCompany")}
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {canEdit && <Link href={`/companies/${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("companies.deactivateBtn")}</Button>}
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-6">
          <Card>
            <CardHeader><CardTitle>{t("companies.infoCardTitle")}</CardTitle></CardHeader>
            <CardContent className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {[
                { icon: <Globe className="w-4 h-4" />, label: t("common.website"), value: company.website ? <a href={company.website} target="_blank" rel="noopener noreferrer" className="text-primary hover:underline text-sm">{company.website}</a> : "—" },
                { icon: <Mail className="w-4 h-4" />, label: t("common.email"), value: company.email ? <a href={`mailto:${company.email}`} className="text-primary hover:underline text-sm">{company.email}</a> : "—" },
                { icon: <Phone className="w-4 h-4" />, label: t("common.phone"), value: company.phone ?? "—" },
                { icon: <MapPin className="w-4 h-4" />, label: t("common.address"), value: [company.city, company.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={company.customFieldData?.definitions ?? []}
                values={company.customFieldData?.values ?? {}}
              />
            </CardContent>
          </Card>

          {/* Customers */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{t("companies.sectionContacts")} ({company._count?.contacts ?? 0})</CardTitle>
              <Link href={`/customers/new?companyId=${id}`}><Button variant="outline" size="sm"><Plus className="w-4 h-4" /> {t("companies.btnAddContact")}</Button></Link>
            </CardHeader>
            <CardContent className="p-0">
              {company.contacts?.length === 0 ? (
                <div className="py-8 text-center text-muted-foreground text-sm">{t("companies.emptyContacts")}</div>
              ) : (
                <div className="divide-y divide-border">
                  {company.contacts?.slice(0, 5).map((c: any) => (
                    <div key={c.id} className="px-6 py-3 flex items-center justify-between">
                      <div>
                        <Link href={`/customers/${c.id}`} className="text-sm font-medium text-primary hover:underline">{c.firstName} {c.lastName}</Link>
                        {c.jobTitle && <p className="text-xs text-muted-foreground">{c.jobTitle}</p>}
                      </div>
                      <span className="text-xs text-muted-foreground">{c.email}</span>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          {/* Deals */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>{t("companies.sectionDeals")} ({company._count?.opportunities ?? 0})</CardTitle>
              <Link href={`/deals/new?companyId=${id}`}><Button variant="outline" size="sm"><Plus className="w-4 h-4" /> {t("companies.btnAddDeal")}</Button></Link>
            </CardHeader>
            <CardContent className="p-0">
              {company.opportunities?.length === 0 ? (
                <div className="py-8 text-center text-muted-foreground text-sm">{t("companies.emptyDeals")}</div>
              ) : (
                <div className="divide-y divide-border">
                  {company.opportunities?.map((d: any) => (
                    <div key={d.id} className="px-6 py-3 flex items-center justify-between">
                      <Link href={`/deals/${d.id}`} className="text-sm font-medium text-primary hover:underline">{d.title}</Link>
                      <div className="flex items-center gap-3">
                        <span className="text-xs text-muted-foreground">{getLabel(DEAL_STAGE_LABELS, DEAL_STAGE_LABELS_AR, d.stage, language)}</span>
                        <span className="text-sm font-semibold">{formatCurrency(d.value, d.currency)}</span>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        <div className="space-y-6">
          <Card>
            <CardHeader><CardTitle>{t("companies.sidebarCard")}</CardTitle></CardHeader>
            <CardContent className="space-y-4">
              {company.revenue && (
                <div>
                  <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("companies.labelAnnualRevenue")}</p>
                  <p className="text-sm font-semibold">{formatCurrency(company.revenue, company.currency)}</p>
                </div>
              )}
              <div>
                <p className="text-xs text-muted-foreground font-medium uppercase tracking-wide mb-1">{t("companies.labelSummary")}</p>
                <div className="space-y-1.5">
                  <div className="flex justify-between text-sm"><span className="text-muted-foreground">{t("companies.summaryContacts")}</span><span className="font-medium">{company._count?.contacts ?? 0}</span></div>
                  <div className="flex justify-between text-sm"><span className="text-muted-foreground">{t("companies.summaryDeals")}</span><span className="font-medium">{company._count?.opportunities ?? 0}</span></div>
                  <div className="flex justify-between text-sm"><span className="text-muted-foreground">{t("companies.summaryActivities")}</span><span className="font-medium">{company._count?.activities ?? 0}</span></div>
                </div>
              </div>
              <div className="pt-2 border-t border-border">
                <div className="flex justify-between text-sm"><span className="text-muted-foreground">{t("companies.labelAdded")}</span><span>{formatDate(company.createdAt, language)}</span></div>
              </div>
            </CardContent>
          </Card>
          {company.notes && (
            <Card>
              <CardHeader><CardTitle>{t("companies.formNotes")}</CardTitle></CardHeader>
              <CardContent><p className="text-sm whitespace-pre-wrap">{company.notes}</p></CardContent>
            </Card>
          )}
        </div>
      </div>

      <ConfirmDialog open={deleteOpen} onClose={() => setDeleteOpen(false)} onConfirm={handleDelete}
        isLoading={isDeleting} title={t("companies.dialogDeactivateTitle")}
        description={t("companies.dialogDeactivateDesc")}
        confirmLabel={t("companies.deactivateBtn")} variant="destructive" />
    </AppShell>
  );
}
