import Link from "next/link";
import { notFound } from "next/navigation";
import { db } from "@/lib/db";
import { AdminPageHeader } from "@/components/admin/page-header";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { LeadStatusManager } from "@/components/admin/lead-status-manager";
import {
  ArrowLeft, Phone, Mail, MessageSquare, Wrench, Clock, Tag,
  User, FileText,
} from "lucide-react";

export const dynamic = "force-dynamic";

const TYPE_STYLES: Record<string, string> = {
  CONTACT: "bg-blue-500/10 text-blue-700 border-blue-500/20",
  QUOTE: "bg-amber-500/10 text-amber-700 border-amber-500/20",
  CALLBACK: "bg-cyan-500/10 text-cyan-700 border-cyan-500/20",
  SERVICE: "bg-emerald-500/10 text-emerald-700 border-emerald-500/20",
  EMERGENCY: "bg-rose-500/10 text-rose-700 border-rose-500/20",
};

function Field({
  icon: Icon,
  label,
  value,
  href,
}: {
  icon: React.ComponentType<{ className?: string }>;
  label: string;
  value: string | null | undefined;
  href?: string;
}) {
  if (!value) return null;
  return (
    <div className="flex items-start gap-3 py-2.5">
      <div className="grid place-items-center size-8 rounded-lg bg-[var(--brand-royal)]/10 text-[var(--brand-royal)] shrink-0 mt-0.5">
        <Icon className="size-4" />
      </div>
      <div className="min-w-0">
        <div className="text-[11px] uppercase tracking-wide text-muted-foreground font-semibold">{label}</div>
        {href ? (
          <a href={href} className="text-sm font-medium hover:underline break-all">{value}</a>
        ) : (
          <div className="text-sm font-medium break-words">{value}</div>
        )}
      </div>
    </div>
  );
}

export default async function AdminLeadDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const lead = await db.lead.findUnique({ where: { id } });
  if (!lead) notFound();

  const created = new Date(lead.createdAt);
  const updated = new Date(lead.updatedAt);

  return (
    <>
      <AdminPageHeader
        title={lead.name}
        description={`Lead received ${created.toLocaleString("en-PK")}`}
      >
        <Button asChild variant="outline" size="sm">
          <Link href="/admin/leads"><ArrowLeft className="size-4 mr-1.5" /> Back to Leads</Link>
        </Button>
      </AdminPageHeader>

      <div className="grid lg:grid-cols-3 gap-6">
        {/* Main content */}
        <div className="lg:col-span-2 space-y-5">
          <Card className="p-6 rounded-2xl space-y-1">
            <div className="flex items-center gap-2 mb-3">
              <Badge variant="outline" className={`text-[10px] font-bold uppercase ${TYPE_STYLES[lead.type] || ""}`}>
                {lead.type}
              </Badge>
              {lead.service && (
                <Badge variant="outline" className="text-[10px] font-bold uppercase">
                  {lead.service}
                </Badge>
              )}
            </div>
            <Field icon={User} label="Name" value={lead.name} />
            <Field icon={Phone} label="Phone" value={lead.phone} href={`tel:${lead.phone}`} />
            {lead.email && (
              <Field icon={Mail} label="Email" value={lead.email} href={`mailto:${lead.email}`} />
            )}
            {lead.subject && (
              <Field icon={Tag} label="Subject" value={lead.subject} />
            )}
            {lead.service && (
              <Field icon={Wrench} label="Service" value={lead.service} />
            )}
            {lead.message && (
              <Field icon={MessageSquare} label="Message" value={lead.message} />
            )}
          </Card>

          {lead.message && (
            <Card className="p-6 rounded-2xl">
              <h2 className="font-bold text-sm uppercase tracking-wide text-muted-foreground mb-3 flex items-center gap-2">
                <FileText className="size-4" /> Full Message
              </h2>
              <p className="text-sm leading-relaxed whitespace-pre-wrap break-words">{lead.message}</p>
            </Card>
          )}
        </div>

        {/* Sidebar */}
        <div className="space-y-5">
          <Card className="p-6 rounded-2xl">
            <h2 className="font-bold mb-4">Manage Lead</h2>
            <LeadStatusManager leadId={lead.id} initialStatus={lead.status} />
          </Card>

          <Card className="p-6 rounded-2xl space-y-2.5">
            <h2 className="font-bold mb-1">Metadata</h2>
            <div className="flex items-start gap-3 py-2">
              <Clock className="size-4 text-muted-foreground shrink-0 mt-0.5" />
              <div>
                <div className="text-[11px] uppercase tracking-wide text-muted-foreground font-semibold">Received</div>
                <div className="text-sm">{created.toLocaleString("en-PK")}</div>
              </div>
            </div>
            <div className="flex items-start gap-3 py-2">
              <Clock className="size-4 text-muted-foreground shrink-0 mt-0.5" />
              <div>
                <div className="text-[11px] uppercase tracking-wide text-muted-foreground font-semibold">Last Updated</div>
                <div className="text-sm">{updated.toLocaleString("en-PK")}</div>
              </div>
            </div>
            <div className="flex items-start gap-3 py-2">
              <Tag className="size-4 text-muted-foreground shrink-0 mt-0.5" />
              <div>
                <div className="text-[11px] uppercase tracking-wide text-muted-foreground font-semibold">Lead ID</div>
                <div className="text-xs font-mono break-all">{lead.id}</div>
              </div>
            </div>
          </Card>

          <Card className="p-6 rounded-2xl">
            <h2 className="font-bold mb-3">Quick Contact</h2>
            <div className="flex flex-col gap-2">
              <Button asChild variant="outline" size="sm">
                <a href={`tel:${lead.phone}`}><Phone className="size-4 mr-1.5" /> Call</a>
              </Button>
              <Button asChild variant="outline" size="sm">
                <a href={`https://wa.me/${lead.phone.replace(/\D/g, "")}`} target="_blank" rel="noreferrer">
                  <MessageSquare className="size-4 mr-1.5" /> WhatsApp
                </a>
              </Button>
              {lead.email && (
                <Button asChild variant="outline" size="sm">
                  <a href={`mailto:${lead.email}`}><Mail className="size-4 mr-1.5" /> Email</a>
                </Button>
              )}
            </div>
          </Card>
        </div>
      </div>
    </>
  );
}
