"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Lead, Activity, Reminder } 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 } from "@/app/admin/leads/actions";
import { formatDistanceToNow, format } from "date-fns";
import { it } from "date-fns/locale";
import { LogActivityModal } from "./LogActivityModal";
import { SendQuoteModal } from "./SendQuoteModal";
import { EditLeadModal } from "./LeadForm";

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,
}: {
  lead: Lead;
  activities: Activity[];
  reminders: Reminder[];
  tags: string[];
  tagOptions: string[];
}) {
  const router = useRouter();
  const [, startTransition] = useTransition();
  const [tagError, setTagError] = useState<string | null>(null);

  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");
      }
    });
  }

  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} />
          <SendQuoteModal leadId={lead.id} />
          <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>
    </div>
  );
}
