"use client";

import { useEffect, useState, useCallback } from "react";
import { X, Pencil, Trash2, Send, Clock, Plus, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
import { createClient } from "@/lib/supabase/client";
import type { Lead, LeadNote, LeadActivity, LeadStatus, LeadScore, Profile } from "@/types";
import { LEAD_STATUSES, LEAD_SCORES, getStatusMeta, getScoreMeta, formatValue } from "@/lib/leads-config";

type Props = {
  lead: Lead;
  teamMembers?: Profile[];
  onClose: () => void;
  onEdit: () => void;
  onDeleted: () => void;
  onLeadUpdated: (lead: Lead) => void;
};

export function LeadDetailPanel({ lead, teamMembers = [], onClose, onEdit, onDeleted, onLeadUpdated }: Props) {
  const supabase = createClient();
  const [notes, setNotes] = useState<LeadNote[]>([]);
  const [activities, setActivities] = useState<LeadActivity[]>([]);
  const [noteText, setNoteText] = useState("");
  const [savingNote, setSavingNote] = useState(false);
  const [tab, setTab] = useState<"info" | "notes" | "activity">("info");

  const load = useCallback(async () => {
    const [{ data: n }, { data: a }] = await Promise.all([
      supabase.from("lead_notes").select("*, profiles(full_name,avatar_url)").eq("lead_id", lead.id).order("created_at", { ascending: false }),
      supabase.from("lead_activities").select("*, profiles(full_name,avatar_url)").eq("lead_id", lead.id).order("created_at", { ascending: false }),
    ]);
    setNotes((n ?? []) as LeadNote[]);
    setActivities((a ?? []) as LeadActivity[]);
  }, [supabase, lead.id]);

  // queueMicrotask: react-hooks/set-state-in-effect flags calling `load`
  // (which setStates) directly in the effect body — defer by one tick.
  useEffect(() => { queueMicrotask(() => { load(); }); }, [load]);

  async function getUserId() {
    const { data: { user } } = await supabase.auth.getUser();
    return user?.id;
  }

  async function addNote() {
    if (!noteText.trim()) return;
    setSavingNote(true);
    const uid = await getUserId();
    if (!uid) { setSavingNote(false); return; }
    const { data } = await supabase.from("lead_notes").insert({
      lead_id: lead.id, user_id: uid, content: noteText.trim(), team_id: lead.team_id ?? null,
    }).select("*, profiles(full_name,avatar_url)").single();
    await supabase.from("lead_activities").insert({
      lead_id: lead.id, user_id: uid, type: "note", description: "Notiz hinzugefügt", team_id: lead.team_id ?? null,
    });
    if (data) setNotes((p) => [data as LeadNote, ...p]);
    setNoteText("");
    setSavingNote(false);
  }

  async function deleteNote(id: string) {
    await supabase.from("lead_notes").delete().eq("id", id);
    setNotes((p) => p.filter((n) => n.id !== id));
  }

  async function handleDelete() {
    if (!confirm(`"${lead.name}" wirklich löschen?`)) return;
    await supabase.from("leads").delete().eq("id", lead.id);
    onDeleted();
  }

  async function updateStatus(status: LeadStatus) {
    const uid = await getUserId();
    const { data } = await supabase.from("leads").update({ status }).eq("id", lead.id).select().single();
    if (data) {
      onLeadUpdated(data as Lead);
      if (uid) await supabase.from("lead_activities").insert({
        lead_id: lead.id, user_id: uid, type: "status_change",
        description: `Status → ${getStatusMeta(status).label}`,
      });
      await load();
    }
  }

  async function updateScore(score: LeadScore) {
    const uid = await getUserId();
    const { data } = await supabase.from("leads").update({ score }).eq("id", lead.id).select().single();
    if (data) {
      onLeadUpdated(data as Lead);
      if (uid) await supabase.from("lead_activities").insert({
        lead_id: lead.id, user_id: uid, type: "score_change",
        description: `Temperatur → ${getScoreMeta(score).label}`,
      });
      await load();
    }
  }

  const sm = getStatusMeta(lead.status);
  const sc = getScoreMeta(lead.score);

  return (
    <div className="flex w-80 shrink-0 flex-col border-l border-white/[0.05] bg-[#0a0a0e] overflow-hidden">
      {/* Header */}
      <div className="flex items-start justify-between border-b border-white/[0.05] px-4 py-3.5">
        <div className="min-w-0 flex-1 pr-2">
          <div className="truncate text-[14px] font-semibold text-white">{lead.name}</div>
          {lead.company && <div className="text-[11px] text-white/40 truncate">{lead.company}</div>}
        </div>
        <div className="flex items-center gap-1 shrink-0">
          <button onClick={onEdit} className="rounded p-1 text-white/25 hover:text-white/60 transition-colors"><Pencil className="h-3.5 w-3.5" /></button>
          <button onClick={handleDelete} className="rounded p-1 text-white/25 hover:text-red-400 transition-colors"><Trash2 className="h-3.5 w-3.5" /></button>
          <button onClick={onClose} className="rounded p-1 text-white/25 hover:text-white/60 transition-colors"><X className="h-4 w-4" /></button>
        </div>
      </div>

      {/* Quick status + score change */}
      <div className="flex items-center gap-2 border-b border-white/[0.04] px-4 py-2.5">
        <div className="flex-1">
          <div className="mb-1 text-[10px] text-white/30">Status</div>
          <div className="flex flex-wrap gap-1">
            {LEAD_STATUSES.map((s) => (
              <button
                key={s.value}
                onClick={() => s.value !== lead.status && updateStatus(s.value)}
                className={cn(
                  "rounded-full border px-2 py-0.5 text-[10px] font-medium transition-all",
                  lead.status === s.value ? cn(s.bg, s.color) : "border-white/[0.06] text-white/25 hover:border-white/20 hover:text-white/50"
                )}
              >{s.label}</button>
            ))}
          </div>
        </div>
      </div>
      <div className="flex items-center gap-2 border-b border-white/[0.04] px-4 py-2.5">
        <div className="flex-1">
          <div className="mb-1 text-[10px] text-white/30">Temperatur</div>
          <div className="flex gap-1">
            {LEAD_SCORES.map((s) => (
              <button
                key={s.value}
                onClick={() => s.value !== lead.score && updateScore(s.value)}
                className={cn(
                  "rounded-lg border px-2.5 py-1 text-[11px] font-medium transition-all",
                  lead.score === s.value
                    ? cn("border-white/20 bg-white/[0.06]", s.color)
                    : "border-white/[0.06] text-white/25 hover:border-white/15 hover:text-white/50"
                )}
              >{s.emoji} {s.label}</button>
            ))}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex border-b border-white/[0.04]">
        {(["info","notes","activity"] as const).map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            className={cn(
              "flex-1 py-2 text-[11px] font-medium transition-colors capitalize",
              tab === t ? "border-b-2 border-indigo-500 text-white" : "text-white/30 hover:text-white/60"
            )}
          >
            {t === "info" ? "Info" : t === "notes" ? `Notizen (${notes.length})` : "Verlauf"}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div className="flex-1 overflow-y-auto">
        {tab === "info" && (
          <div className="px-4 py-3 space-y-3">
            <InfoRow label="Kategorie" value={lead.category} />
            <InfoRow label="Wert" value={formatValue(lead.value)} />
            <InfoRow label="Quelle" value={lead.source ?? "—"} />
            {lead.assigned_to && (() => {
              const member = teamMembers.find((m) => m.id === lead.assigned_to);
              return member ? <InfoRow label="Zugewiesen" value={
                <span className="flex items-center gap-1.5">
                  <span className="inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-indigo-500/20 text-[9px] font-bold text-indigo-400">
                    {(member.full_name || member.email).charAt(0).toUpperCase()}
                  </span>
                  {member.full_name || member.email}
                </span>
              } /> : null;
            })()}
            {lead.email && <InfoRow label="E-Mail" value={<a href={`mailto:${lead.email}`} className="text-indigo-400 hover:underline">{lead.email}</a>} />}
            {lead.phone && <InfoRow label="Telefon" value={<a href={`tel:${lead.phone}`} className="text-indigo-400 hover:underline">{lead.phone}</a>} />}
            <InfoRow label="Erstellt" value={new Date(lead.created_at).toLocaleDateString("de-DE", { day:"2-digit", month:"short", year:"numeric" })} />
            <InfoRow label="Zuletzt" value={new Date(lead.updated_at).toLocaleDateString("de-DE", { day:"2-digit", month:"short", year:"numeric" })} />
            {lead.notes && (
              <div>
                <div className="text-[10px] text-white/30 mb-1">Notizen</div>
                <div className="rounded-lg bg-white/[0.03] border border-white/[0.05] px-3 py-2 text-[12px] text-white/60 leading-relaxed whitespace-pre-wrap">{lead.notes}</div>
              </div>
            )}
          </div>
        )}

        {tab === "notes" && (
          <div className="flex flex-col h-full">
            <div className="flex-1 overflow-y-auto px-4 py-3 space-y-2">
              {notes.length === 0 && (
                <p className="text-center py-8 text-[12px] text-white/25">Noch keine Notizen</p>
              )}
              {notes.map((n) => {
                const author = n.profiles;
                const initials = author?.full_name ? author.full_name.charAt(0).toUpperCase() : "?";
                return (
                  <div key={n.id} className="group rounded-lg border border-white/[0.05] bg-white/[0.02] px-3 py-2.5">
                    {author && (
                      <div className="flex items-center gap-1.5 mb-1.5">
                        <span className="inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-indigo-500/20 text-[8px] font-bold text-indigo-400">{initials}</span>
                        <span className="text-[10px] text-white/40">{author.full_name || "Unbekannt"}</span>
                      </div>
                    )}
                    <div className="text-[12px] text-white/75 leading-relaxed whitespace-pre-wrap">{n.content}</div>
                    <div className="mt-1.5 flex items-center justify-between">
                      <span className="text-[10px] text-white/25">{new Date(n.created_at).toLocaleDateString("de-DE", { day:"2-digit", month:"short" })} · {new Date(n.created_at).toLocaleTimeString("de-DE", { hour:"2-digit", minute:"2-digit" })}</span>
                      <button onClick={() => deleteNote(n.id)} className="opacity-0 group-hover:opacity-100 text-[10px] text-red-400/60 hover:text-red-400 transition-all">Löschen</button>
                    </div>
                  </div>
                );
              })}
            </div>
            {/* Add note */}
            <div className="border-t border-white/[0.05] px-3 py-3">
              <div className="flex gap-2">
                <textarea
                  value={noteText}
                  onChange={(e) => setNoteText(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) addNote(); }}
                  placeholder="Notiz schreiben… (⌘↵ senden)"
                  rows={2}
                  className="flex-1 resize-none rounded-lg border border-white/[0.07] bg-white/[0.03] px-3 py-2 text-[12px] text-white placeholder:text-white/25 focus:outline-none focus:border-white/20"
                />
                <button
                  onClick={addNote}
                  disabled={savingNote || !noteText.trim()}
                  className="self-end rounded-lg bg-indigo-500/80 p-2 text-white hover:bg-indigo-400 disabled:opacity-40 transition-all"
                >
                  {savingNote ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Send className="h-3.5 w-3.5" />}
                </button>
              </div>
            </div>
          </div>
        )}

        {tab === "activity" && (
          <div className="px-4 py-3">
            {activities.length === 0 && (
              <p className="text-center py-8 text-[12px] text-white/25">Noch keine Aktivitäten</p>
            )}
            <div className="relative space-y-0">
              {activities.map((a, i) => {
                const author = a.profiles;
                return (
                  <div key={a.id} className="flex gap-3 pb-4 relative">
                    <div className="flex flex-col items-center">
                      <div className="z-10 rounded-full bg-white/[0.08] border border-white/[0.08] p-1">
                        <Clock className="h-2.5 w-2.5 text-white/40" />
                      </div>
                      {i < activities.length - 1 && <div className="w-px flex-1 bg-white/[0.05] mt-1" />}
                    </div>
                    <div className="flex-1 min-w-0 pt-0.5">
                      <div className="text-[12px] text-white/70">{a.description}</div>
                      <div className="text-[10px] text-white/25 mt-0.5 flex items-center gap-1.5">
                        {author && <span className="text-white/35">{author.full_name}</span>}
                        {author && <span>·</span>}
                        {new Date(a.created_at).toLocaleDateString("de-DE", { day:"2-digit", month:"short" })} · {new Date(a.created_at).toLocaleTimeString("de-DE", { hour:"2-digit", minute:"2-digit" })}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
  return (
    <div className="flex items-start justify-between gap-2">
      <span className="text-[11px] text-white/30 shrink-0 pt-0.5">{label}</span>
      <span className="text-[12px] text-white/70 text-right">{value}</span>
    </div>
  );
}
