"use client";

// ============================================================
// Pipeline — storm-restoration kanban board.
//   · Head   : title + counts, search
//   · Board  : horizontal stage columns (dot, count, progress
//              bar). Cards are draggable between columns.
//   · Card   : avatar, name, address, work/lead-type pills,
//              rep + storm badge + age.
//   · Drawer : click a card → right slide-over with a stage
//              stepper, Details (contact / job / assignment /
//              notes / timeline) and an Activity trail.
// Data comes from pipeline-data.ts (client-side mock).
// ============================================================

import { useMemo, useState, type DragEvent } from "react";
import { Avatar, Icon, useToast } from "./ui";
import {
  LEADS, STAGES, PROGRESSION, pctFor, buildActivity,
  type PLead, type StageKey,
} from "./pipeline-data";

export function Pipeline() {
  const toast = useToast();
  const [leads, setLeads] = useState<PLead[]>(LEADS);
  const [query, setQuery] = useState("");
  const [selected, setSelected] = useState<PLead | null>(null);
  const [dragId, setDragId] = useState<string | null>(null);
  const [overStage, setOverStage] = useState<StageKey | null>(null);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return leads;
    return leads.filter((l) =>
      `${l.name} ${l.address} ${l.rep} ${l.workType} ${l.id}`.toLowerCase().includes(q));
  }, [leads, query]);

  const byStage = (key: StageKey) => filtered.filter((l) => l.stage === key);

  function moveTo(stage: StageKey) {
    if (!dragId) return;
    setLeads((prev) =>
      prev.map((l) => {
        if (l.id !== dragId) return l;
        // Landing on a progression column advances "reached" if it's further along.
        const inProg = PROGRESSION.indexOf(stage);
        const reached = inProg > PROGRESSION.indexOf(l.reached) ? stage : l.reached;
        return { ...l, stage, reached };
      }));
    const label = STAGES.find((s) => s.key === stage)?.label ?? stage;
    const lead = leads.find((l) => l.id === dragId);
    if (lead && lead.stage !== stage) toast.push({ tone: "success", title: "Lead moved", desc: `${lead.name} → ${label}` });
    setDragId(null);
    setOverStage(null);
  }

  const stageCount = STAGES.filter((s) => !s.flag).length;

  return (
    <div className="view pl">
      {/* ---- head -------------------------------------------- */}
      <div className="pl-head">
        <div className="pl-head-l">
          <span className="pl-head-ic"><Icon name="pipeline" size={20} /></span>
          <div>
            <h1>Pipeline</h1>
            <p>{leads.length} leads · {stageCount} stages</p>
          </div>
        </div>
        <div className="pl-search">
          <Icon name="search" size={16} />
          <input
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            placeholder="Search leads…"
            aria-label="Search leads"
          />
          {query && <button className="pl-search-x" aria-label="Clear" onClick={() => setQuery("")}><Icon name="x" size={14} /></button>}
        </div>
      </div>

      {/* ---- board ------------------------------------------- */}
      <div className="pl-board">
        {STAGES.map((stage) => {
          const items = byStage(stage.key);
          const step = PROGRESSION.indexOf(stage.key);
          return (
            <section
              key={stage.key}
              className={`pl-col ${stage.flag ? "is-flag" : ""} ${overStage === stage.key ? "is-over" : ""}`}
              data-tone={stage.tone}
              onDragOver={(e) => { e.preventDefault(); setOverStage(stage.key); }}
              onDragLeave={() => setOverStage((s) => (s === stage.key ? null : s))}
              onDrop={() => moveTo(stage.key)}
            >
              <header className="pl-col-head">
                <span className="pl-col-dot" />
                <span className="pl-col-label">{stage.label}</span>
                <span className="pl-col-count">{items.length}</span>
                {step >= 0 && <span className="pl-col-step">{step + 1}/{stageCount}</span>}
              </header>
              <div className="pl-col-bar"><span style={{ width: step >= 0 ? `${((step + 1) / stageCount) * 100}%` : "100%" }} /></div>

              <div className="pl-col-body">
                {items.map((l) => (
                  <PipelineCard
                    key={l.id}
                    lead={l}
                    onOpen={() => setSelected(l)}
                    onDragStart={() => setDragId(l.id)}
                    onDragEnd={() => { setDragId(null); setOverStage(null); }}
                    dragging={dragId === l.id}
                  />
                ))}
                {items.length === 0 && <div className="pl-col-empty">Drop leads here</div>}
              </div>
            </section>
          );
        })}
      </div>

      <LeadDrawer lead={selected} onClose={() => setSelected(null)} />
    </div>
  );
}

/* ---------------------------------------------------------- */
/* Card                                                        */
/* ---------------------------------------------------------- */

function PipelineCard({ lead, onOpen, onDragStart, onDragEnd, dragging }: {
  lead: PLead; onOpen: () => void; onDragStart: () => void; onDragEnd: () => void; dragging: boolean;
}) {
  return (
    <article
      className={`pl-card ${dragging ? "is-dragging" : ""}`}
      draggable
      onDragStart={(e) => { e.dataTransfer.effectAllowed = "move"; onDragStart(); }}
      onDragEnd={onDragEnd}
      onClick={onOpen}
      role="button"
      tabIndex={0}
      onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onOpen(); } }}
    >
      <div className="pl-card-top">
        <Avatar initials={lead.initials} gradient={lead.gradient} size={38} square />
        <div className="pl-card-id">
          <div className="pl-card-name">{lead.name}</div>
          <div className="pl-card-addr"><Icon name="pin" size={12} /> {lead.address}</div>
        </div>
      </div>
      <div className="pl-card-tags">
        <span className="pl-tag work">{lead.workType}</span>
        <span className="pl-tag type">{lead.leadType}</span>
      </div>
      <div className="pl-card-foot">
        <span className="pl-rep"><Icon name="user" size={12} /> {lead.rep}</span>
        <span className="pl-card-spacer" />
        {lead.storm && <span className="pl-storm"><Icon name="storm" size={12} /> Storm</span>}
        <span className="pl-age"><Icon name="clock" size={12} /> {lead.ageDays}d</span>
      </div>
    </article>
  );
}

/* ---------------------------------------------------------- */
/* Detail drawer                                               */
/* ---------------------------------------------------------- */

function LeadDrawer({ lead, onClose }: { lead: PLead | null; onClose: () => void }) {
  const toast = useToast();
  const [tab, setTab] = useState<"details" | "activity">("details");
  if (!lead) return null;

  const stage = STAGES.find((s) => s.key === lead.stage);
  const pct = pctFor(lead.reached);
  const reachedIdx = PROGRESSION.indexOf(lead.reached);
  const progStages = STAGES.filter((s) => PROGRESSION.includes(s.key));
  const activity = buildActivity(lead);

  return (
    <>
      <div className="pl-scrim" onClick={onClose} />
      <aside className="pl-drawer" data-tone={stage?.tone} role="dialog" aria-label={`${lead.name} details`}>
        <div className="pl-drawer-head">
          <Avatar initials={lead.initials} gradient={lead.gradient} size={44} square />
          <div className="pl-drawer-id">
            <div className="pl-drawer-name">{lead.name}</div>
            <div className="pl-drawer-addr">{lead.address}, {lead.city} {lead.state} {lead.zip}</div>
          </div>
          <button className="pl-drawer-x" aria-label="Close" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        {/* status + stepper */}
        <div className="pl-drawer-status">
          <div className="pl-status-row">
            <span className="pl-status-label">{stage?.label}</span>
            <span className="pl-status-pct">{pct}%</span>
          </div>
          <div className="pl-status-bar"><span style={{ width: `${pct}%` }} /></div>
          <div className="pl-steps">
            {progStages.map((s, i) => (
              <span key={s.key} className={`pl-step ${i <= reachedIdx ? "done" : ""}`} data-tone={s.tone}>
                <i className="pl-step-dot" />
                <span className="pl-step-label">{s.label}</span>
              </span>
            ))}
          </div>
        </div>

        <div className="pl-drawer-tabs" role="tablist">
          <button role="tab" aria-selected={tab === "details"} className={tab === "details" ? "active" : ""} onClick={() => setTab("details")}>Details</button>
          <button role="tab" aria-selected={tab === "activity"} className={tab === "activity" ? "active" : ""} onClick={() => setTab("activity")}>Activity</button>
        </div>

        <div className="pl-drawer-body">
          {tab === "details" ? (
            <>
              <DSection title="Contact">
                <div className="pl-contact"><Icon name="phone" size={14} /> {lead.phone}</div>
                <div className="pl-contact"><Icon name="mail" size={14} /> {lead.email}</div>
                <div className="pl-contact"><Icon name="pin" size={14} /> {lead.address}, {lead.city} {lead.state} {lead.zip}</div>
              </DSection>

              <DSection title="Job Details">
                <div className="pl-jobgrid">
                  <div className="pl-jobbox"><span className="pl-jobk">Type</span><span className="pl-jobv">{lead.workType}</span></div>
                  <div className="pl-jobbox"><span className="pl-jobk">Category</span><span className="pl-jobv">{lead.leadType}</span></div>
                </div>
              </DSection>

              <DSection title="Assignment">
                <div className="pl-assign"><Icon name="user" size={14} /> {lead.rep}</div>
              </DSection>

              <DSection title="Notes">
                <div className="pl-notes">{lead.notes}</div>
              </DSection>

              <DSection title="Timeline">
                <div className="pl-contact"><Icon name="clock" size={14} /> Created {lead.createdAt}</div>
              </DSection>
            </>
          ) : (
            <div className="pl-activity">
              {activity.map((a, i) => (
                <div className="pl-act" key={i}>
                  <span className="pl-act-node" />
                  <div className="pl-act-body">
                    <div className="pl-act-head">
                      {a.from ? <><span className="pl-act-from">{a.from}</span> <Icon name="arrow" size={12} /> <span className="pl-act-to">{a.to}</span></> : <span className="pl-act-to">{a.to}</span>}
                    </div>
                    <div className="pl-act-meta">by {a.by} · {a.date}</div>
                    {a.note && <div className="pl-act-note">{a.note}</div>}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="pl-drawer-foot">
          <button className="pl-more" onClick={() => toast.push({ tone: "info", title: "Full lead record", desc: `${lead.id} · ${lead.name}` })}>
            <Icon name="arrow" size={15} /> More Details
          </button>
        </div>
      </aside>
    </>
  );
}

function DSection({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="pl-dsec">
      <div className="pl-dsec-head">{title}</div>
      <div className="pl-dsec-body">{children}</div>
    </div>
  );
}
