"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Lead, Activity, Reminder, ClientTranscript } from "@/db/schema";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { OptionMultiSelect } from "@/components/ui/option-multi-select";
import {
  addLeadTag,
  removeLeadTag,
  renameLeadTag,
  deleteTranscript,
  convertLeadToClient,
} from "@/app/admin/leads/actions";
import { formatDistanceToNow, format } from "date-fns";
import { it } from "date-fns/locale";
import Link from "next/link";
import { LogActivityModal } from "./LogActivityModal";
import { SendQuoteModal } from "./SendQuoteModal";
import { EditLeadModal } from "./LeadForm";
import { TranscriptModal } from "./TranscriptModal";

const ACTIVITY_ICON: Record<string, string> = {
  call: "📞",
  email: "📧",
  meeting: "📅",
  note: "📝",
};

const STAGE_COLOR: Record<string, string> = {
  contacted: "bg-blue-100 text-blue-800",
  qualified: "bg-purple-100 text-purple-800",
  proposal_sent: "bg-amber-100 text-amber-800",
  negotiating: "bg-orange-100 text-orange-800",
  won: "bg-green-100 text-green-800",
  lost: "bg-red-100 text-red-800",
};

export function LeadDetail({
  lead,
  activities,
  reminders,
  tags,
  tagOptions,
  transcripts,
  convertedClientId,
}: {
  lead: Lead;
  activities: Activity[];
  reminders: Reminder[];
  tags: string[];
  tagOptions: string[];
  transcripts: ClientTranscript[];
  convertedClientId?: string | null;
}) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [converting, startConvert] = useTransition();
  const [tagError, setTagError] = useState<string | null>(null);
  const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
  const [deletingId, setDeletingId] = useState<string | null>(null);

  function handleConvert() {
    const ok = window.confirm(
      `Convertire "${lead.name}" in cliente?\n\nVerrà creato un cliente (con email, telefono e transcript del lead) e il lead verrà archiviato mantenendo lo stato "vinto".`
    );
    if (!ok) return;
    startConvert(() => convertLeadToClient(lead.id));
  }

  function run(fn: () => Promise<unknown>) {
    setTagError(null);
    startTransition(async () => {
      try {
        await fn();
        router.refresh();
      } catch (e) {
        setTagError(e instanceof Error ? e.message : "Errore nel salvataggio");
      }
    });
  }

  function toggleExpand(id: string) {
    setExpandedIds((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function handleDeleteTranscript(transcriptId: string) {
    setDeletingId(transcriptId);
    startTransition(async () => {
      try {
        await deleteTranscript(transcriptId, lead.id);
        router.refresh();
      } catch (e) {
        console.error("deleteTranscript error:", e);
      } finally {
        setDeletingId(null);
      }
    });
  }

  return (
    <div className="space-y-6">
      {/* Header + Actions */}
      <div className="flex justify-between items-start">
        <div>
          <h1 className="text-3xl font-bold">{lead.name}</h1>
          <p className="text-gray-600">{lead.company || "Azienda non specificata"}</p>
        </div>
        <div className="flex gap-2">
          <LogActivityModal leadId={lead.id} />
          <TranscriptModal leadId={lead.id} />
          <SendQuoteModal leadId={lead.id} />
          <Link
            href={`/admin/preventivi/genera?lead_id=${lead.id}`}
            className="inline-flex items-center gap-1.5 px-3 py-2 bg-[#DEF168] text-[#1A463C] rounded-md text-sm font-semibold hover:bg-[#d4e85e] transition-colors"
          >
            Genera preventivo
          </Link>
          {convertedClientId ? (
            <Link
              href={`/admin/clients/${convertedClientId}`}
              className="inline-flex items-center gap-1.5 px-3 py-2 bg-[#1A463C]/10 text-[#1A463C] rounded-md text-sm font-semibold hover:bg-[#1A463C]/15 transition-colors"
            >
              ✓ Convertito → Apri cliente
            </Link>
          ) : (
            lead.status === "won" && (
              <button
                type="button"
                onClick={handleConvert}
                disabled={converting}
                className="inline-flex items-center gap-1.5 px-3 py-2 bg-[#1A463C] text-white rounded-md text-sm font-semibold hover:bg-[#1A463C]/90 transition-colors disabled:opacity-50"
              >
                {converting ? "Conversione..." : "Converti in cliente"}
              </button>
            )
          )}
          <EditLeadModal lead={lead} />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {/* Lead Profile Card */}
        <Card>
          <CardHeader>
            <CardTitle>Profilo</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="text-sm text-gray-600">Stato</label>
              <Badge className={STAGE_COLOR[lead.status as keyof typeof STAGE_COLOR] || ""}>
                {lead.status.replace(/_/g, " ")}
              </Badge>
            </div>
            <div>
              <label className="text-sm text-gray-600">Tag</label>
              <OptionMultiSelect
                values={tags}
                options={tagOptions}
                onAdd={(v) => run(() => addLeadTag(lead.id, v))}
                onRemove={(v) => run(() => removeLeadTag(lead.id, v))}
                onRename={(o, n) => run(() => renameLeadTag(o, n))}
              />
              {tagError && <p className="text-xs text-red-600 mt-1">{tagError}</p>}
            </div>
            <div>
              <label className="text-sm text-gray-600">Email</label>
              <p>{lead.email || "—"}</p>
            </div>
            <div>
              <label className="text-sm text-gray-600">Telefono</label>
              <p>{lead.phone || "—"}</p>
            </div>
            <div>
              <label className="text-sm text-gray-600">Ultimo contatto</label>
              <p>
                {lead.last_contact_date
                  ? formatDistanceToNow(new Date(lead.last_contact_date), {
                      addSuffix: true,
                      locale: it,
                    })
                  : "—"}
              </p>
            </div>
            <div>
              <label className="text-sm text-gray-600">Prossima azione</label>
              <p className="font-medium">{lead.next_action || "—"}</p>
            </div>
          </CardContent>
        </Card>

        {/* Upcoming Reminders Card */}
        <Card>
          <CardHeader>
            <CardTitle>Prossimi Follow-up</CardTitle>
          </CardHeader>
          <CardContent>
            {reminders.length > 0 ? (
              <ul className="space-y-2">
                {reminders.map((r) => (
                  <li key={r.id} className="text-sm border-l-2 border-blue-300 pl-2">
                    <p className="font-medium">{r.title}</p>
                    <p className="text-gray-600">
                      {format(new Date(r.due_date), "dd MMM yyyy", { locale: it })}
                    </p>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="text-gray-500 text-sm">Nessun reminder</p>
            )}
          </CardContent>
        </Card>

        {/* Notes Card */}
        <Card>
          <CardHeader>
            <CardTitle>Note</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm">{lead.notes || "Nessuna nota"}</p>
          </CardContent>
        </Card>
      </div>

      {/* Activity Log */}
      <Card>
        <CardHeader>
          <CardTitle>Storico Attività</CardTitle>
        </CardHeader>
        <CardContent>
          {activities.length > 0 ? (
            <div className="space-y-4">
              {activities.map((activity) => (
                <div key={activity.id} className="border-l-4 border-blue-300 pl-4 pb-4">
                  <div className="flex items-center gap-2">
                    <span className="text-xl">
                      {ACTIVITY_ICON[activity.type as keyof typeof ACTIVITY_ICON] || "📝"}
                    </span>
                    <span className="font-medium capitalize">{activity.type}</span>
                    <span className="text-gray-600 text-sm">
                      {formatDistanceToNow(new Date(activity.activity_date), {
                        addSuffix: true,
                        locale: it,
                      })}
                    </span>
                  </div>
                  <p className="text-sm mt-2">{activity.notes}</p>
                  {activity.duration_minutes && (
                    <p className="text-xs text-gray-500 mt-1">
                      Durata: {activity.duration_minutes} minuti
                    </p>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <p className="text-gray-500 text-sm">Nessuna attività registrata</p>
          )}
        </CardContent>
      </Card>

      {/* Transcript Call */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>Transcript Call</CardTitle>
          <span className="text-sm text-gray-500">
            {transcripts.length} {transcripts.length === 1 ? "transcript" : "transcript"}
          </span>
        </CardHeader>
        <CardContent>
          {transcripts.length > 0 ? (
            <div className="space-y-4">
              {transcripts.map((t) => {
                const isExpanded = expandedIds.has(t.id);
                const formattedDate = format(
                  new Date(t.call_date + "T00:00:00"),
                  "d MMMM yyyy",
                  { locale: it }
                );
                const lines = t.content.split("\n");
                const preview = lines.slice(0, 3).join("\n").slice(0, 200);
                const hasMore = t.content.length > preview.length || lines.length > 3;

                return (
                  <div key={t.id} className="border-l-4 border-purple-300 pl-4 pb-4">
                    <div className="flex items-start justify-between gap-2">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 flex-wrap">
                          <span className="font-medium text-sm">{formattedDate}</span>
                          {t.title && (
                            <span className="text-gray-600 text-sm">— {t.title}</span>
                          )}
                        </div>
                        <div className="mt-2 text-sm text-gray-700 whitespace-pre-wrap">
                          {isExpanded ? t.content : preview}
                          {!isExpanded && hasMore && (
                            <span className="text-gray-400">...</span>
                          )}
                        </div>
                        {hasMore && (
                          <button
                            onClick={() => toggleExpand(t.id)}
                            className="text-xs text-blue-600 hover:underline mt-1"
                          >
                            {isExpanded ? "Mostra meno" : "Mostra tutto"}
                          </button>
                        )}
                      </div>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-red-600 hover:text-red-700 shrink-0"
                        disabled={deletingId === t.id}
                        onClick={() => handleDeleteTranscript(t.id)}
                      >
                        {deletingId === t.id ? "..." : "Elimina"}
                      </Button>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <p className="text-gray-500 text-sm">Nessun transcript registrato</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
