"use client";

import { useEffect, useState, useRef, useCallback } from "react";
import {
  Plus, Upload, Download, Search, X,
  TrendingUp, Users, Trophy, Flame, Euro,
  ChevronUp, ChevronDown, ChevronsUpDown,
  Pencil, Trash2, Eye, Lightbulb, AlertTriangle, CheckCircle2,
  UserCheck,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { createClient } from "@/lib/supabase/client";
import { useWorkspaceStore } from "@/stores/workspace-store";
import type { Lead, LeadStatus, LeadScore } from "@/types";
import type { Profile } from "@/types";
import {
  LEAD_CATEGORIES, LEAD_SOURCES, LEAD_STATUSES, LEAD_SCORES,
  getStatusMeta, getScoreMeta, formatValue,
} from "@/lib/leads-config";
import { getScalingTip } from "@/lib/leads-scaling-tips";
import { LeadFormModal } from "@/components/leads/lead-form-modal";
import { LeadDetailPanel } from "@/components/leads/lead-detail-panel";

// ── CSV helpers ──────────────────────────────────────────────────────────────

function leadsToCSV(leads: Lead[]): string {
  const headers = ["Name","Firma","E-Mail","Telefon","Kategorie","Status","Score","Quelle","Wert (€)","Notizen","Erstellt"];
  const rows = leads.map((l) => [
    l.name, l.company ?? "", l.email ?? "", l.phone ?? "",
    l.category, l.status, l.score, l.source ?? "",
    l.value != null ? String(l.value) : "",
    (l.notes ?? "").replace(/\n/g, " "),
    new Date(l.created_at).toLocaleDateString("de-DE"),
  ].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(","));
  return [headers.join(","), ...rows].join("\n");
}

function downloadCSV(content: string, filename: string) {
  const blob = new Blob(["﻿" + content], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url; a.download = filename; a.click();
  URL.revokeObjectURL(url);
}

function parseCSV(text: string): Partial<Lead>[] {
  const lines = text.split(/\r?\n/).filter(Boolean);
  if (lines.length < 2) return [];
  const parse = (line: string) => {
    const cells: string[] = [];
    let cur = "", inQ = false;
    for (const ch of line) {
      if (ch === '"') { inQ = !inQ; }
      else if (ch === "," && !inQ) { cells.push(cur.trim()); cur = ""; }
      else { cur += ch; }
    }
    cells.push(cur.trim());
    return cells;
  };
  const headers = parse(lines[0]).map((h) => h.toLowerCase());
  const col = (row: string[], name: string) => {
    const i = headers.findIndex((h) => h.includes(name));
    return i >= 0 ? row[i]?.replace(/^"|"$/g, "").trim() : undefined;
  };
  return lines.slice(1).map((line) => {
    const row = parse(line);
    const status = col(row, "status") as LeadStatus | undefined;
    const score  = col(row, "score")  as LeadScore  | undefined;
    return {
      name:     col(row, "name")     || "Unbekannt",
      company:  col(row, "firma")    || col(row, "company"),
      email:    col(row, "mail"),
      phone:    col(row, "telefon")  || col(row, "phone"),
      category: col(row, "kategorie") || col(row, "category") || "Sonstiges",
      status:   (["neu","kontaktiert","angebot","gewonnen","verloren"] as LeadStatus[]).includes(status!) ? status : "neu",
      score:    (["cold","warm","hot"] as LeadScore[]).includes(score!) ? score : "cold",
      source:   col(row, "quelle")   || col(row, "source"),
      value: (() => {
        const raw = col(row, "wert");
        if (!raw) return null;
        const parsed = parseFloat(raw.replace(",", "."));
        return Number.isFinite(parsed) ? parsed : null;
      })(),
      notes:    col(row, "notizen")  || col(row, "notes"),
    };
  }).filter((l) => l.name);
}

// ── Sort helper ───────────────────────────────────────────────────────────────

type SortKey = "name" | "category" | "status" | "score" | "value" | "created_at";
type SortDir = "asc" | "desc";

function sortLeads(leads: Lead[], key: SortKey, dir: SortDir): Lead[] {
  return [...leads].sort((a, b) => {
    let av: string | number = a[key] as string | number ?? "";
    let bv: string | number = b[key] as string | number ?? "";
    if (key === "value") { av = a.value ?? -1; bv = b.value ?? -1; }
    if (key === "created_at") { av = new Date(a.created_at).getTime(); bv = new Date(b.created_at).getTime(); }
    const statusOrder: Record<LeadStatus, number> = { neu: 0, kontaktiert: 1, angebot: 2, gewonnen: 3, verloren: 4 };
    const scoreOrder:  Record<LeadScore, number>  = { cold: 0, warm: 1, hot: 2 };
    if (key === "status") { av = statusOrder[a.status]; bv = statusOrder[b.status]; }
    if (key === "score")  { av = scoreOrder[a.score];   bv = scoreOrder[b.score]; }
    if (av < bv) return dir === "asc" ? -1 : 1;
    if (av > bv) return dir === "asc" ? 1 : -1;
    return 0;
  });
}

// ── Page ─────────────────────────────────────────────────────────────────────

export default function LeadsPage() {
  const supabase = createClient();
  const activeTeamId = useWorkspaceStore((s) => s.activeTeamId);
  const [leads, setLeads] = useState<Lead[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentUserId, setCurrentUserId] = useState<string | null>(null);
  const [teamMembers, setTeamMembers] = useState<Profile[]>([]);

  // filters
  const [search, setSearch] = useState("");
  const [filterStatus, setFilterStatus] = useState<LeadStatus | "all">("all");
  const [filterScore,  setFilterScore]  = useState<LeadScore  | "all">("all");
  const [filterCategory, setFilterCategory] = useState("all");
  const [filterMine, setFilterMine] = useState(false);

  // sort
  const [sortKey, setSortKey] = useState<SortKey>("created_at");
  const [sortDir, setSortDir] = useState<SortDir>("desc");

  // modals
  const [formOpen, setFormOpen] = useState(false);
  const [editLead, setEditLead] = useState<Lead | null>(null);
  const [detailLead, setDetailLead] = useState<Lead | null>(null);

  // import
  const fileRef = useRef<HTMLInputElement>(null);
  const [importing, setImporting] = useState(false);

  // ── Load ────────────────────────────────────────────────────────────────────

  const load = useCallback(async () => {
    let query = supabase.from("leads").select("*").order("created_at", { ascending: false });
    query = activeTeamId ? query.eq("team_id", activeTeamId) : query.is("team_id", null);
    const { data } = await query;
    setLeads((data as Lead[]) ?? []);
    setLoading(false);
  }, [activeTeamId, supabase]);

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

  // Load team members when in a team workspace
  useEffect(() => {
    if (!activeTeamId) { queueMicrotask(() => setTeamMembers([])); return; }
    supabase
      .from("team_members")
      .select("profiles(id,full_name,avatar_url)")
      .eq("team_id", activeTeamId)
      .then(({ data }) => {
        const members = (data ?? [])
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          .map((row: any) => Array.isArray(row.profiles) ? row.profiles[0] : row.profiles)
          .filter(Boolean) as Profile[];
        setTeamMembers(members);
      });
  }, [activeTeamId, supabase]);

  // ── Derived data ─────────────────────────────────────────────────────────────

  const total       = leads.length;
  const won         = leads.filter((l) => l.status === "gewonnen");
  const lost        = leads.filter((l) => l.status === "verloren");
  const hotLeads    = leads.filter((l) => l.score === "hot" && l.status !== "gewonnen" && l.status !== "verloren");
  const closed      = won.length + lost.length;
  const convRate    = closed > 0 ? Math.round((won.length / closed) * 100) : null;
  const pipeline    = leads
    .filter((l) => l.status !== "gewonnen" && l.status !== "verloren")
    .reduce((s, l) => s + (l.value ?? 0), 0);
  const wonValue    = won.reduce((s, l) => s + (l.value ?? 0), 0);

  const tip = getScalingTip(leads);

  const isTeamWorkspace = !!activeTeamId;

  // filtered + sorted
  const filtered = sortLeads(
    leads.filter((l) => {
      if (filterMine && l.user_id !== currentUserId && l.assigned_to !== currentUserId) return false;
      if (filterStatus !== "all" && l.status !== filterStatus) return false;
      if (filterScore  !== "all" && l.score  !== filterScore)  return false;
      if (filterCategory !== "all" && l.category !== filterCategory) return false;
      if (search) {
        const q = search.toLowerCase();
        return l.name.toLowerCase().includes(q)
          || (l.company ?? "").toLowerCase().includes(q)
          || (l.email   ?? "").toLowerCase().includes(q);
      }
      return true;
    }),
    sortKey, sortDir
  );

  // ── Sort toggle ───────────────────────────────────────────────────────────────

  function toggleSort(key: SortKey) {
    if (sortKey === key) setSortDir((d) => d === "asc" ? "desc" : "asc");
    else { setSortKey(key); setSortDir("asc"); }
  }

  function SortIcon({ k }: { k: SortKey }) {
    if (sortKey !== k) return <ChevronsUpDown className="h-3 w-3 opacity-30" />;
    return sortDir === "asc"
      ? <ChevronUp className="h-3 w-3 text-white/60" />
      : <ChevronDown className="h-3 w-3 text-white/60" />;
  }

  // ── Delete ────────────────────────────────────────────────────────────────────

  async function handleDelete(lead: Lead) {
    if (!confirm(`"${lead.name}" wirklich löschen?`)) return;
    await supabase.from("leads").delete().eq("id", lead.id);
    setLeads((prev) => prev.filter((l) => l.id !== lead.id));
    if (detailLead?.id === lead.id) setDetailLead(null);
  }

  // ── Import CSV ────────────────────────────────────────────────────────────────

  async function handleImport(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    setImporting(true);
    const text = await file.text();
    const rows = parseCSV(text);
    if (rows.length === 0) { setImporting(false); return; }
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) { setImporting(false); return; }
    const inserts = rows.map((r) => ({ ...r, user_id: user.id, team_id: activeTeamId ?? null }));
    await supabase.from("leads").insert(inserts);
    await load();
    setImporting(false);
    if (fileRef.current) fileRef.current.value = "";
  }

  // ── Refresh after form save ───────────────────────────────────────────────────

  function handleSaved(lead: Lead) {
    setLeads((prev) => {
      const idx = prev.findIndex((l) => l.id === lead.id);
      if (idx >= 0) { const n = [...prev]; n[idx] = lead; return n; }
      return [lead, ...prev];
    });
    if (detailLead?.id === lead.id) setDetailLead(lead);
  }

  // ── Render ────────────────────────────────────────────────────────────────────

  return (
    <div className="flex h-full overflow-hidden">
      {/* ── Main content ── */}
      <div className="flex flex-1 flex-col overflow-hidden">

        {/* Header */}
        <div className="flex items-center justify-between border-b border-white/[0.05] px-6 py-4">
          <div>
            <div className="flex items-center gap-2">
              <h1 className="text-lg font-semibold text-white">Leads</h1>
              {isTeamWorkspace && (
                <span className="rounded-full border border-indigo-500/30 bg-indigo-500/10 px-2 py-0.5 text-[10px] font-medium text-indigo-400">Team</span>
              )}
            </div>
            <p className="text-[12px] text-white/40">{total} Kontakte · {hotLeads.length} heiß{isTeamWorkspace && teamMembers.length > 0 ? ` · ${teamMembers.length} Mitglieder` : ""}</p>
          </div>
          <div className="flex items-center gap-2">
            <input ref={fileRef} type="file" accept=".csv" className="hidden" onChange={handleImport} />
            <button
              onClick={() => fileRef.current?.click()}
              disabled={importing}
              className="flex items-center gap-1.5 rounded-lg border border-white/[0.07] bg-white/[0.03] px-3 py-1.5 text-[12px] text-white/50 transition-all hover:border-white/[0.12] hover:text-white/70 disabled:opacity-50"
            >
              <Upload className="h-3.5 w-3.5" />
              {importing ? "Importiere…" : "CSV Import"}
            </button>
            <button
              onClick={() => downloadCSV(leadsToCSV(filtered), `leads-${new Date().toISOString().slice(0,10)}.csv`)}
              className="flex items-center gap-1.5 rounded-lg border border-white/[0.07] bg-white/[0.03] px-3 py-1.5 text-[12px] text-white/50 transition-all hover:border-white/[0.12] hover:text-white/70"
            >
              <Download className="h-3.5 w-3.5" />
              Export
            </button>
            <button
              onClick={() => { setEditLead(null); setFormOpen(true); }}
              className="flex items-center gap-1.5 rounded-lg bg-indigo-500 px-3 py-1.5 text-[12px] font-medium text-white transition-all hover:bg-indigo-400"
            >
              <Plus className="h-3.5 w-3.5" />
              Lead hinzufügen
            </button>
          </div>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-5 space-y-5">

          {/* Stats */}
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
            <StatCard icon={<Users className="h-4 w-4" />} label="Gesamt" value={String(total)} color="text-sky-400" />
            <StatCard icon={<TrendingUp className="h-4 w-4" />} label="Conversion" value={convRate != null ? `${convRate} %` : "—"} color="text-violet-400" />
            <StatCard icon={<Trophy className="h-4 w-4" />} label="Gewonnen" value={String(won.length)} sub={wonValue > 0 ? formatValue(wonValue) : undefined} color="text-emerald-400" />
            <StatCard icon={<Euro className="h-4 w-4" />} label="Pipeline" value={formatValue(pipeline)} color="text-amber-400" />
            <StatCard icon={<Flame className="h-4 w-4" />} label="Heiße Leads" value={String(hotLeads.length)} color="text-orange-400" />
          </div>

          {/* Scaling Tip */}
          <ScalingTipCard tip={tip} />

          {/* Filters */}
          <div className="flex flex-wrap items-center gap-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-white/30" />
              <input
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder="Suche…"
                className="h-8 rounded-lg border border-white/[0.07] bg-white/[0.03] pl-8 pr-3 text-[12px] text-white placeholder:text-white/25 focus:outline-none focus:border-white/20 w-48"
              />
            </div>

            {/* Mine filter — only in team workspace */}
            {isTeamWorkspace && (
              <button
                onClick={() => setFilterMine((v) => !v)}
                className={cn(
                  "flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-[11px] font-medium transition-all",
                  filterMine
                    ? "border-indigo-500/40 bg-indigo-500/10 text-indigo-400"
                    : "border-white/[0.07] text-white/40 hover:border-white/15 hover:text-white/60"
                )}
              >
                <UserCheck className="h-3 w-3" /> Nur meine
              </button>
            )}

            {/* Status tabs */}
            <div className="flex items-center gap-1 rounded-lg border border-white/[0.07] bg-white/[0.02] p-1">
              {([{value:"all",label:"Alle"},...LEAD_STATUSES.map(s=>({value:s.value,label:s.label}))] as {value:string;label:string}[]).map((s) => (
                <button
                  key={s.value}
                  onClick={() => setFilterStatus(s.value as LeadStatus | "all")}
                  className={cn(
                    "rounded-md px-2.5 py-0.5 text-[11px] font-medium transition-all",
                    filterStatus === s.value
                      ? "bg-white/[0.08] text-white"
                      : "text-white/40 hover:text-white/60"
                  )}
                >{s.label}</button>
              ))}
            </div>

            {/* Score filter */}
            <select
              value={filterScore}
              onChange={(e) => setFilterScore(e.target.value as LeadScore | "all")}
              className="h-8 rounded-lg border border-white/[0.07] bg-[#0a0a0d] px-2 text-[12px] text-white/60 focus:outline-none"
            >
              <option value="all">Alle Temperaturen</option>
              {LEAD_SCORES.map((s) => <option key={s.value} value={s.value}>{s.emoji} {s.label}</option>)}
            </select>

            {/* Category filter */}
            <select
              value={filterCategory}
              onChange={(e) => setFilterCategory(e.target.value)}
              className="h-8 rounded-lg border border-white/[0.07] bg-[#0a0a0d] px-2 text-[12px] text-white/60 focus:outline-none"
            >
              <option value="all">Alle Kategorien</option>
              {LEAD_CATEGORIES.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>

            {(search || filterStatus !== "all" || filterScore !== "all" || filterCategory !== "all" || filterMine) && (
              <button
                onClick={() => { setSearch(""); setFilterStatus("all"); setFilterScore("all"); setFilterCategory("all"); setFilterMine(false); }}
                className="flex items-center gap-1 rounded-lg px-2 py-1 text-[11px] text-white/30 hover:text-white/60"
              >
                <X className="h-3 w-3" /> Filter zurücksetzen
              </button>
            )}

            <span className="ml-auto text-[11px] text-white/25">{filtered.length} Ergebnisse</span>
          </div>

          {/* Table */}
          {loading ? (
            <div className="flex items-center justify-center py-16 text-white/30 text-sm">Lade Leads…</div>
          ) : filtered.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16 gap-3 text-white/30">
              <Users className="h-8 w-8 opacity-40" />
              <p className="text-sm">Keine Leads gefunden</p>
              {total === 0 && (
                <button onClick={() => { setEditLead(null); setFormOpen(true); }} className="mt-1 text-[12px] text-indigo-400 hover:text-indigo-300">
                  Ersten Lead hinzufügen →
                </button>
              )}
            </div>
          ) : (
            <div className="rounded-xl border border-white/[0.06] overflow-hidden">
              <div className="overflow-x-auto">
              <table className="w-full min-w-[640px] text-[12px]">
                <thead>
                  <tr className="border-b border-white/[0.05] bg-white/[0.02]">
                    {(
                      [
                        { key: "name" as SortKey, label: "Name / Firma" },
                        { key: "category" as SortKey, label: "Kategorie" },
                        { key: "status" as SortKey, label: "Status" },
                        { key: "score" as SortKey, label: "Score" },
                        { key: "value" as SortKey, label: "Wert" },
                        { key: "created_at" as SortKey, label: "Erstellt" },
                      ] as { key: SortKey; label: string }[]
                    ).map(({ key, label }) => (
                      <th key={key} className="px-4 py-2.5 text-left font-medium text-white/30">
                        <button onClick={() => toggleSort(key)} className="flex items-center gap-1 hover:text-white/60 transition-colors">
                          {label} <SortIcon k={key} />
                        </button>
                      </th>
                    ))}
                    <th className="px-4 py-2.5" />
                  </tr>
                </thead>
                <tbody className="divide-y divide-white/[0.03]">
                  {filtered.map((lead) => {
                    const sm = getStatusMeta(lead.status);
                    const sc = getScoreMeta(lead.score);
                    return (
                      <tr
                        key={lead.id}
                        onClick={() => setDetailLead(lead)}
                        className={cn(
                          "cursor-pointer transition-colors hover:bg-white/[0.025]",
                          detailLead?.id === lead.id && "bg-white/[0.04]"
                        )}
                      >
                        <td className="px-4 py-3">
                          <div className="font-medium text-white/90">{lead.name}</div>
                          {lead.company && <div className="text-white/35">{lead.company}</div>}
                        </td>
                        <td className="px-4 py-3 text-white/50">{lead.category}</td>
                        <td className="px-4 py-3">
                          <span className={cn("rounded-full border px-2 py-0.5 text-[10px] font-medium", sm.bg, sm.color)}>
                            {sm.label}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <span className={cn("font-medium", sc.color)}>{sc.emoji} {sc.label}</span>
                        </td>
                        <td className="px-4 py-3 text-white/60 font-mono">{formatValue(lead.value)}</td>
                        <td className="px-4 py-3 text-white/30">
                          {new Date(lead.created_at).toLocaleDateString("de-DE")}
                        </td>
                        <td className="px-4 py-3">
                          <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                            <button
                              onClick={() => setDetailLead(lead)}
                              className="rounded p-1 text-white/25 hover:text-white/60 transition-colors"
                            ><Eye className="h-3.5 w-3.5" /></button>
                            <button
                              onClick={() => { setEditLead(lead); setFormOpen(true); }}
                              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(lead)}
                              className="rounded p-1 text-white/25 hover:text-red-400 transition-colors"
                            ><Trash2 className="h-3.5 w-3.5" /></button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* ── Detail Panel ── */}
      {detailLead && (
        <LeadDetailPanel
          lead={detailLead}
          teamMembers={teamMembers}
          onClose={() => setDetailLead(null)}
          onEdit={() => { setEditLead(detailLead); setFormOpen(true); }}
          onDeleted={() => { setLeads((p) => p.filter((l) => l.id !== detailLead.id)); setDetailLead(null); }}
          onLeadUpdated={(l) => { setDetailLead(l); handleSaved(l); }}
        />
      )}

      {/* ── Form Modal ── */}
      {formOpen && (
        <LeadFormModal
          lead={editLead}
          teamId={activeTeamId ?? null}
          teamMembers={teamMembers}
          onClose={() => { setFormOpen(false); setEditLead(null); }}
          onSaved={handleSaved}
        />
      )}
    </div>
  );
}

// ── Sub-components ────────────────────────────────────────────────────────────

function StatCard({ icon, label, value, sub, color }: {
  icon: React.ReactNode; label: string; value: string; sub?: string; color: string;
}) {
  return (
    <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] px-4 py-3">
      <div className={cn("mb-2 w-fit rounded-lg bg-white/[0.04] p-1.5", color)}>{icon}</div>
      <div className="text-[11px] text-white/40">{label}</div>
      <div className="text-xl font-semibold text-white mt-0.5">{value}</div>
      {sub && <div className="text-[11px] text-white/30 mt-0.5">{sub}</div>}
    </div>
  );
}

function ScalingTipCard({ tip }: { tip: ReturnType<typeof getScalingTip> }) {
  const icons = {
    info:    <Lightbulb className="h-4 w-4 text-sky-400" />,
    warning: <AlertTriangle className="h-4 w-4 text-yellow-400" />,
    success: <CheckCircle2 className="h-4 w-4 text-emerald-400" />,
  };
  const borders = {
    info:    "border-sky-400/15 bg-sky-400/[0.04]",
    warning: "border-yellow-400/15 bg-yellow-400/[0.04]",
    success: "border-emerald-400/15 bg-emerald-400/[0.04]",
  };
  return (
    <div className={cn("rounded-xl border px-4 py-3.5 flex items-start gap-3", borders[tip.urgency])}>
      <div className="mt-0.5 shrink-0">{icons[tip.urgency]}</div>
      <div>
        <div className="text-[12px] font-semibold text-white/90 mb-0.5">
          Scaling-Tipp: {tip.title}
        </div>
        <div className="text-[12px] text-white/55 leading-relaxed">{tip.body}</div>
      </div>
    </div>
  );
}
