"use client";

import { use, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  CalendarClock,
  FileText,
  Save,
  Trash2,
  Clock,
  Plus,
  MessageSquare,
  ArrowRight,
  HelpCircle,
  PlusCircle,
} from "lucide-react";
import { motion } from "framer-motion";
import Button from "@/components/ui/Button";
import Input from "@/components/ui/Input";
import {
  createPresupuestoFromOportunidad,
  getCrmOportunidad,
  updateCrmOportunidad,
  deleteCrmOportunidad,
  listCrmActividades,
  logCrmActividad,
  deleteCrmActividad,
} from "@/lib/pb/crm";
import { listPresupuestos } from "@/lib/pb/presupuestos";
import { crmEstimatedValue } from "@/lib/crm/domain";
import { useUnsavedChangesGuard } from "@/lib/useUnsavedChangesGuard";
import {
  ESTADO_CRM_LABELS,
  ORIGEN_CRM_LABELS,
  PRIORIDAD_CRM_LABELS,
  type CrmOportunidad,
  type EstadoCrm,
  type OrigenCrm,
  type PrioridadCrm,
  type CrmActividad,
} from "@/lib/types/crm";
import type { Presupuesto } from "@/lib/types/presupuesto";
import { dateShort, money } from "@/lib/format";

function getActivityIcon(tipo: string) {
  switch (tipo) {
    case "creacion":
      return PlusCircle;
    case "cambio_estado":
      return ArrowRight;
    case "presupuesto_asociado":
      return FileText;
    case "comentario_usuario":
      return MessageSquare;
    case "contacto":
      return CalendarClock;
    default:
      return HelpCircle;
  }
}

export default function CrmDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [item, setItem] = useState<CrmOportunidad | null>(null);
  const [titulo, setTitulo] = useState("");
  const [origen, setOrigen] = useState<OrigenCrm>("whatsapp");
  const [estado, setEstado] = useState<EstadoCrm>("nuevo");
  const [prioridad, setPrioridad] = useState<PrioridadCrm>("media");
  const [valorEstimado, setValorEstimado] = useState("");
  const [proximoContacto, setProximoContacto] = useState("");
  const [nota, setNota] = useState("");
  const [presupuestoId, setPresupuestoId] = useState("");
  const [clientBudgets, setClientBudgets] = useState<Presupuesto[]>([]);
  const [activities, setActivities] = useState<CrmActividad[]>([]);
  const [newNote, setNewNote] = useState("");
  const [addingNote, setAddingNote] = useState(false);
  const [savedSnapshot, setSavedSnapshot] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");

  function snapshot() {
    return JSON.stringify({
      titulo: titulo.trim(),
      origen,
      estado,
      prioridad,
      valorEstimado: Number(valorEstimado) || 0,
      proximoContacto,
      nota: nota.trim(),
      presupuestoId,
    });
  }

  async function reload() {
    const loaded = await getCrmOportunidad(id);
    setItem(loaded);
    setTitulo(loaded.titulo || "");
    setOrigen(loaded.origen);
    setEstado(loaded.estado);
    setPrioridad(loaded.prioridad);
    setValorEstimado(String(crmEstimatedValue(loaded) || ""));
    setProximoContacto((loaded.proximo_contacto || "").slice(0, 10));
    setNota(loaded.nota || "");
    setPresupuestoId(loaded.presupuesto || "");

    if (loaded.cliente) {
      try {
        const budgetsRes = await listPresupuestos({ cliente: loaded.cliente });
        setClientBudgets(budgetsRes.items || []);
      } catch (errBudgets) {
        console.error("Error al cargar presupuestos del cliente", errBudgets);
      }
    }

    try {
      const acts = await listCrmActividades(id);
      setActivities(acts);
    } catch (errActs) {
      console.error("Error al cargar actividades del CRM", errActs);
    }

    setSavedSnapshot(JSON.stringify({
      titulo: (loaded.titulo || "").trim(),
      origen: loaded.origen,
      estado: loaded.estado,
      prioridad: loaded.prioridad,
      valorEstimado: crmEstimatedValue(loaded),
      proximoContacto: (loaded.proximo_contacto || "").slice(0, 10),
      nota: (loaded.nota || "").trim(),
      presupuestoId: loaded.presupuesto || "",
    }));
  }

  useEffect(() => {
    (async () => {
      try {
        await reload();
      } catch (e) {
        setErr((e as Error).message || "No se pudo cargar la oportunidad");
      } finally {
        setLoading(false);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const hasUnsavedChanges = Boolean(savedSnapshot && savedSnapshot !== snapshot());
  useUnsavedChangesGuard(hasUnsavedChanges && !saving, save);

  async function save() {
    if (!titulo.trim()) {
      setErr("Falta el nombre del trabajo u oportunidad");
      return;
    }
    setSaving(true);
    setErr("");
    try {
      let targetEstado = estado;
      if (presupuestoId) {
        const selectedBudget = clientBudgets.find(b => b.id === presupuestoId);
        if (selectedBudget && selectedBudget.total === 0) {
          targetEstado = "presupuestar";
          setEstado("presupuestar");
        }
      }

      const updated = await updateCrmOportunidad(id, {
        titulo: titulo.trim(),
        origen,
        estado: targetEstado,
        prioridad,
        valor_estimado: Number(valorEstimado) || 0,
        proximo_contacto: proximoContacto || "",
        nota: nota.trim(),
        presupuesto: presupuestoId || "",
      });
      setItem(updated);
      
      const nextSnapshot = JSON.stringify({
        titulo: titulo.trim(),
        origen,
        estado: targetEstado,
        prioridad,
        valorEstimado: Number(valorEstimado) || 0,
        proximoContacto,
        nota: nota.trim(),
        presupuestoId,
      });
      setSavedSnapshot(nextSnapshot);
      
      // Reload activities in case automated log was registered
      const acts = await listCrmActividades(id);
      setActivities(acts);
    } catch (e) {
      setErr((e as Error).message || "No se pudo guardar");
    } finally {
      setSaving(false);
    }
  }

  async function handleDelete() {
    if (!confirm("¿Está seguro de que desea eliminar esta oportunidad?")) return;
    setSaving(true);
    setErr("");
    try {
      await deleteCrmOportunidad(id);
      router.push("/crm");
    } catch (e) {
      setErr((e as Error).message || "No se pudo eliminar la oportunidad");
      setSaving(false);
    }
  }

  async function createBudget() {
    if (!item) return;
    setSaving(true);
    setErr("");
    try {
      await save();
      const presupuesto = await createPresupuestoFromOportunidad(item);
      if (presupuesto?.id) router.replace(`/presupuestos/${presupuesto.id}`);
    } catch (e) {
      setErr((e as Error).message || "No se pudo crear presupuesto");
      setSaving(false);
    }
  }

  async function handleAddNote() {
    if (!newNote.trim()) return;
    setAddingNote(true);
    try {
      await logCrmActividad(id, "comentario_usuario", "Nota de seguimiento", newNote.trim());
      const acts = await listCrmActividades(id);
      setActivities(acts);
      setNewNote("");
    } catch (e) {
      alert((e as Error).message || "No se pudo guardar la nota");
    } finally {
      setAddingNote(false);
    }
  }

  async function handleDeleteActivity(actId: string) {
    if (!confirm("¿Borrar esta nota del historial?")) return;
    try {
      await deleteCrmActividad(actId);
      setActivities((prev) => prev.filter((a) => a.id !== actId));
    } catch (e) {
      alert((e as Error).message || "No se pudo eliminar la nota");
    }
  }

  if (loading) return <div className="py-12 text-center text-sm text-faint">Cargando oportunidad...</div>;
  if (!item) return <div className="py-12 text-center text-bad">{err || "Oportunidad no encontrada"}</div>;

  return (
    <div className="max-w-5xl">
      <div className="mb-6 flex items-center gap-3">
        <Link href="/crm" className="text-ink-soft hover:text-ink"><ArrowLeft size={20} /></Link>
        <div className="flex-1">
          <h1 className="text-2xl font-extrabold text-ink">{item.titulo}</h1>
          <p className="text-sm text-ink-soft">
            {item.expand?.cliente?.nombre || "Cliente"} · creado {dateShort(item.created)}
          </p>
        </div>
        {item.expand?.presupuesto && (
          <Link href={`/presupuestos/${item.presupuesto}`} className="rounded-xl bg-brand-soft px-3 py-2 text-sm font-bold text-brand-dark">
            Presupuesto {item.expand.presupuesto.codigo}
          </Link>
        )}
      </div>

      <div className="grid grid-cols-1 gap-5 lg:grid-cols-3">
        {/* Form Panel */}
        <motion.section initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} className="card space-y-4 p-5 lg:col-span-2">
          <Input label="Trabajo / oportunidad" value={titulo} onChange={(e) => setTitulo(e.target.value)} />
          <div className="grid grid-cols-1 gap-3 md:grid-cols-5">
            <Select label="Origen" value={origen} onChange={(v) => setOrigen(v as OrigenCrm)} options={ORIGEN_CRM_LABELS} />
            <Select label="Estado" value={estado} onChange={(v) => setEstado(v as EstadoCrm)} options={ESTADO_CRM_LABELS} />
            <Select label="Prioridad" value={prioridad} onChange={(v) => setPrioridad(v as PrioridadCrm)} options={PRIORIDAD_CRM_LABELS} />
            <Input label="Valor estimado" type="number" value={valorEstimado} onChange={(e) => setValorEstimado(e.target.value)} />
            <label className="flex flex-col gap-1.5">
              <span className="text-sm font-medium text-ink-soft">Presupuesto</span>
              <select
                value={presupuestoId}
                onChange={(e) => setPresupuestoId(e.target.value)}
                className="h-11 rounded-xl border border-line bg-surface px-3 text-sm outline-none focus:border-brand"
              >
                <option value="">(Sin vincular)</option>
                {clientBudgets.map((b) => (
                  <option key={b.id} value={b.id}>
                    {b.codigo} ({money(b.total)})
                  </option>
                ))}
              </select>
            </label>
          </div>
          <Input label="Próximo seguimiento" type="date" value={proximoContacto} onChange={(e) => setProximoContacto(e.target.value)} prefix={<CalendarClock size={16} />} />
          <label className="flex flex-col gap-1.5">
            <span className="text-sm font-medium text-ink-soft">Nota rápida</span>
            <textarea
              value={nota}
              onChange={(e) => setNota(e.target.value)}
              rows={4}
              className="rounded-xl border border-line bg-surface px-3 py-2 text-sm text-ink outline-none focus:border-brand"
            />
          </label>
          <div className="rounded-xl border border-line bg-canvas p-4 text-sm text-ink-soft">
            <div className="font-semibold text-ink">Cliente</div>
            <div>{item.expand?.cliente?.nombre || "-"}</div>
            <div>{[item.expand?.cliente?.celular, item.expand?.cliente?.direccion].filter(Boolean).join(" · ")}</div>
            <div className="mt-2 font-semibold text-ink">Estimado: {money(crmEstimatedValue({ valor_estimado: Number(valorEstimado) || 0, expand: item.expand }))}</div>
          </div>
        </motion.section>

        {/* Activity Log Panel */}
        <motion.section
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.08 }}
          className="card flex flex-col p-5 space-y-4 h-fit"
        >
          <h2 className="flex items-center gap-2 font-extrabold text-ink border-b border-line/40 pb-2">
            <Clock size={16} className="text-brand-dark" /> Bitácora de seguimiento
          </h2>
          
          {/* New note text area */}
          <div className="space-y-2">
            <textarea
              placeholder="Escribir una nota de seguimiento..."
              value={newNote}
              onChange={(e) => setNewNote(e.target.value)}
              className="w-full rounded-xl border border-line bg-surface p-3 text-xs text-ink outline-none focus:border-brand"
              rows={3}
            />
            <Button
              type="button"
              size="sm"
              className="w-full h-9"
              loading={addingNote}
              onClick={handleAddNote}
              disabled={!newNote.trim()}
            >
              <Plus size={12} /> Agregar nota
            </Button>
          </div>

          {/* Activities list */}
          <div className="flex-1 overflow-y-auto space-y-4 pr-1 max-h-[350px] lg:max-h-[450px]">
            {activities.length === 0 ? (
              <div className="text-center py-8 text-xs text-faint">
                Sin actividades registradas.
              </div>
            ) : (
              activities.map((act) => {
                const Icon = getActivityIcon(act.tipo);
                const userName = act.expand?.created_by?.name || "Sistema";
                return (
                  <div key={act.id} className="relative pl-6 pb-1 border-l border-line/50 last:border-l-0 text-xs">
                    <span className="absolute -left-3 top-0 grid place-items-center h-6 w-6 rounded-full border border-line bg-surface text-faint">
                      <Icon size={12} className="text-brand-dark" />
                    </span>
                    <div className="flex items-center justify-between gap-2">
                      <span className="font-bold text-ink">{act.titulo}</span>
                      <span className="text-[10px] text-faint font-semibold">
                        {dateShort(act.created)}
                      </span>
                    </div>
                    {act.descripcion && (
                      <p className="mt-1 text-ink-soft whitespace-pre-wrap">{act.descripcion}</p>
                    )}
                    <div className="mt-1 flex items-center justify-between text-[10px] text-faint">
                      <span>Por: {userName}</span>
                      {act.tipo === "comentario_usuario" && (
                        <button
                          type="button"
                          onClick={() => handleDeleteActivity(act.id)}
                          className="text-bad hover:underline font-semibold"
                        >
                          Eliminar
                        </button>
                      )}
                    </div>
                  </div>
                );
              })
            )}
          </div>
        </motion.section>

        <div className="lg:col-span-3 flex flex-wrap items-center justify-between gap-3 w-full">
          <div>
            <Button type="button" variant="danger" onClick={handleDelete} loading={saving}>
              <Trash2 size={16} /> Eliminar
            </Button>
          </div>
          <div className="flex flex-wrap items-center gap-3">
            {err && <span className="text-sm font-medium text-bad">{err}</span>}
            <Button type="button" variant="secondary" onClick={save} loading={saving}><Save size={16} /> Guardar</Button>
            <Button type="button" onClick={createBudget} loading={saving} disabled={Boolean(item.presupuesto)}>
              <FileText size={16} /> Crear presupuesto
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

function Select({ label, value, onChange, options }: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  options: Record<string, string>;
}) {
  return (
    <label className="flex flex-col gap-1.5">
      <span className="text-sm font-medium text-ink-soft">{label}</span>
      <select value={value} onChange={(e) => onChange(e.target.value)} className="h-11 rounded-xl border border-line bg-surface px-3 text-sm outline-none focus:border-brand">
        {Object.entries(options).map(([key, label]) => <option key={key} value={key}>{label}</option>)}
      </select>
    </label>
  );
}
