"use client";

import dynamic from "next/dynamic";
import Link from "next/link";
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";

import { apiFetch } from "@/lib/api";
import { cardStyle as cardStyleBase } from "@/lib/adminStyles";

const cardStyle = { ...cardStyleBase, marginTop: 16 };

const ReactECharts = dynamic(() => import("echarts-for-react"), { ssr: false });

interface FunnelMonthRow {
  month: string | null;
  source: string;
  leads: number;
  engaged: number;
  converted: number;
  conv_pct: number | null;
}

interface FunnelSourceRow {
  source: string;
  leads: number;
  engaged: number;
  converted: number;
  conv_pct: number | null;
}

interface LeadRow {
  lead_id: number;
  created_at: string | null;
  source: string | null;
  channel: string | null;
  name: string | null;
  phone_last4: string | null;
  email_hash: string | null;
  obj_interest: number | null;
  obj_name: string | null;
  rooms: number | null;
  budget_min: number | null;
  budget_max: number | null;
  status: string | null;
  converted: boolean | null;
  deal_id: number | null;
  deal_price: number | null;
  deal_closed_at: string | null;
}

interface LeadsResponse {
  total: number;
  limit: number;
  offset: number;
  rows: LeadRow[];
}

interface LeadsStats {
  leads_total: number;
  leads_window: number;
  converted_window: number;
  conv_pct_window: number | null;
  sources_total: number;
  revenue_total: number | null;
  deals_total: number;
  window_months: number;
}

export default function AdminLeadsPage() {
  const [statusFilter, setStatusFilter] = useState<string>("");
  const [sourceFilter, setSourceFilter] = useState<string>("");
  const [convertedFilter, setConvertedFilter] = useState<string>("");
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(0);
  const limit = 50;

  const stats = useQuery({
    queryKey: ["admin-leads-stats"],
    queryFn: () => apiFetch<LeadsStats>("/api/v1/admin/leads/stats?months=12"),
  });

  const funnelBySource = useQuery({
    queryKey: ["admin-leads-funnel-source"],
    queryFn: () =>
      apiFetch<FunnelSourceRow[]>(
        "/api/v1/admin/leads/funnel/by-source?months=12",
      ),
  });

  const funnelMonthly = useQuery({
    queryKey: ["admin-leads-funnel-monthly"],
    queryFn: () =>
      apiFetch<FunnelMonthRow[]>(
        "/api/v1/admin/leads/funnel/monthly?months=24",
      ),
  });

  const sankeyOption = useMemo(() => {
    const rows = funnelBySource.data ?? [];
    if (rows.length === 0) {
      return {
        title: {
          text: "Нет CRM-данных (импортируй prinzip_crm.sqlite)",
          left: "center",
          top: "middle",
          textStyle: { color: "#9ca3af", fontSize: 13, fontWeight: 400 },
        },
      };
    }
    const nodes = [
      { name: "Все заявки" },
      { name: "Engaged" },
      { name: "Converted (deals)" },
      ...rows.map((r) => ({ name: `📥 ${r.source}` })),
    ];
    const links = [
      ...rows.map((r) => ({
        source: `📥 ${r.source}`,
        target: "Все заявки",
        value: r.leads,
      })),
      {
        source: "Все заявки",
        target: "Engaged",
        value: rows.reduce((s, r) => s + r.engaged, 0),
      },
      {
        source: "Engaged",
        target: "Converted (deals)",
        value: rows.reduce((s, r) => s + r.converted, 0),
      },
    ];
    return {
      tooltip: { trigger: "item" },
      series: [
        {
          type: "sankey",
          data: nodes,
          links,
          label: { fontSize: 12 },
          lineStyle: { color: "gradient", curveness: 0.5 },
          emphasis: { focus: "adjacency" },
        },
      ],
    };
  }, [funnelBySource.data]);

  const monthlyOption = useMemo(() => {
    const rows = funnelMonthly.data ?? [];
    if (rows.length === 0) {
      return {
        title: {
          text: "Нет CRM-данных",
          left: "center",
          top: "middle",
          textStyle: { color: "#9ca3af", fontSize: 13, fontWeight: 400 },
        },
      };
    }
    const byMonth: Record<
      string,
      { leads: number; engaged: number; converted: number }
    > = {};
    for (const r of rows) {
      const m = (r.month ?? "").slice(0, 7);
      if (!byMonth[m]) byMonth[m] = { leads: 0, engaged: 0, converted: 0 };
      byMonth[m].leads += r.leads;
      byMonth[m].engaged += r.engaged;
      byMonth[m].converted += r.converted;
    }
    const months = Object.keys(byMonth).sort();
    return {
      tooltip: { trigger: "axis" },
      legend: { data: ["Заявки", "Engaged", "Сделки", "Conversion %"] },
      grid: { left: 56, right: 64, top: 40, bottom: 36 },
      xAxis: { type: "category", data: months },
      yAxis: [
        { type: "value", name: "шт", position: "left" },
        {
          type: "value",
          name: "%",
          position: "right",
          axisLabel: { formatter: "{value}%" },
        },
      ],
      series: [
        {
          name: "Заявки",
          type: "bar",
          data: months.map((m) => byMonth[m].leads),
          itemStyle: { color: "#9ca3af" },
        },
        {
          name: "Engaged",
          type: "bar",
          data: months.map((m) => byMonth[m].engaged),
          itemStyle: { color: "#3b82f6" },
        },
        {
          name: "Сделки",
          type: "bar",
          data: months.map((m) => byMonth[m].converted),
          itemStyle: { color: "#0a7a3a" },
        },
        {
          name: "Conversion %",
          type: "line",
          yAxisIndex: 1,
          smooth: true,
          data: months.map((m) =>
            byMonth[m].leads > 0
              ? Math.round((byMonth[m].converted / byMonth[m].leads) * 1000) /
                10
              : null,
          ),
          lineStyle: { color: "#c2410c", width: 2 },
          itemStyle: { color: "#c2410c" },
        },
      ],
    };
  }, [funnelMonthly.data]);

  const sources = useQuery({
    queryKey: ["admin-leads-sources"],
    queryFn: () => apiFetch<string[]>("/api/v1/admin/leads/sources"),
  });

  const leads = useQuery({
    queryKey: [
      "admin-leads",
      statusFilter,
      sourceFilter,
      convertedFilter,
      search,
      page,
    ],
    queryFn: () => {
      const qs = new URLSearchParams();
      qs.set("limit", String(limit));
      qs.set("offset", String(page * limit));
      if (statusFilter) qs.set("status", statusFilter);
      if (sourceFilter) qs.set("source", sourceFilter);
      if (convertedFilter !== "") qs.set("converted", convertedFilter);
      if (search) qs.set("search", search);
      return apiFetch<LeadsResponse>(`/api/v1/admin/leads/?${qs.toString()}`);
    },
  });

  const fmtMoney = (v: number | null) =>
    v == null
      ? "—"
      : v >= 1e6
        ? `${(v / 1e6).toFixed(2)} М ₽`
        : v.toLocaleString("ru");

  if (stats.isError || leads.isError) {
    const err = String(stats.error ?? leads.error ?? "");
    return (
      <div
        style={{
          padding: 16,
          background: "#fef2f2",
          border: "1px solid #fecaca",
          borderRadius: 6,
          color: "#991b1b",
        }}
      >
        Ошибка: {err}
        <div style={{ marginTop: 8, fontSize: 12 }}>
          Если БД пустая — это нормально. Импортируй CRM:{" "}
          <code>python data/sql/52_import_prinzip_crm.py</code>
        </div>
      </div>
    );
  }

  return (
    <>
      <h2 style={{ marginTop: 0, fontSize: 18 }}>Лиды PRINZIP — CRM воронка</h2>
      <p style={{ color: "#5b6066", fontSize: 13, marginTop: 4 }}>
        Заявки и сделки из <code>analytics.prinzipevent.ru</code>. PII
        (телефон/email) хешированы при импорте — для UI только последние 4 цифры
        телефона.
      </p>

      {/* Funnel charts */}
      <section
        style={{
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          gap: 16,
          marginTop: 16,
        }}
      >
        <div style={cardStyle}>
          <h3 style={{ margin: "0 0 8px", fontSize: 14, fontWeight: 600 }}>
            Воронка CRM (по source)
          </h3>
          <p style={{ margin: "0 0 8px", fontSize: 11, color: "#73767e" }}>
            Sankey leads → engaged → converted из prinzip_leads.
          </p>
          <div style={{ height: 320 }}>
            <ReactECharts
              option={sankeyOption}
              style={{ height: "100%", width: "100%" }}
              notMerge
            />
          </div>
        </div>
        <div style={cardStyle}>
          <h3 style={{ margin: "0 0 8px", fontSize: 14, fontWeight: 600 }}>
            Конверсия по месяцам
          </h3>
          <p style={{ margin: "0 0 8px", fontSize: 11, color: "#73767e" }}>
            Заявки + Engaged + Сделки + Conversion %.
          </p>
          <div style={{ height: 320 }}>
            <ReactECharts
              option={monthlyOption}
              style={{ height: "100%", width: "100%" }}
              notMerge
            />
          </div>
        </div>
      </section>

      {/* KPI cards */}
      <section
        style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 16 }}
      >
        <Card label="Всего заявок" value={stats.data?.leads_total ?? "—"} />
        <Card
          label="За 12 мес"
          value={stats.data?.leads_window ?? "—"}
          hint={`${stats.data?.converted_window ?? 0} конверт.`}
        />
        <Card
          label="Conversion (12 мес)"
          value={
            stats.data?.conv_pct_window != null
              ? `${stats.data.conv_pct_window}%`
              : "—"
          }
        />
        <Card
          label="Revenue (всего)"
          value={fmtMoney(stats.data?.revenue_total ?? null)}
          hint={`${stats.data?.deals_total ?? 0} сделок`}
        />
        <Card label="Источников" value={stats.data?.sources_total ?? "—"} />
      </section>

      {/* Filters */}
      <section style={cardStyle}>
        <div
          style={{
            display: "flex",
            gap: 12,
            flexWrap: "wrap",
            alignItems: "flex-end",
          }}
        >
          <Filter label="Поиск (имя или 4 посл. цифры)">
            <input
              value={search}
              onChange={(e) => {
                setSearch(e.target.value);
                setPage(0);
              }}
              placeholder="Иван / 1234"
              style={inputStyle}
            />
          </Filter>
          <Filter label="Статус">
            <select
              value={statusFilter}
              onChange={(e) => {
                setStatusFilter(e.target.value);
                setPage(0);
              }}
              style={inputStyle}
            >
              <option value="">Все</option>
              <option value="new">new</option>
              <option value="contacted">contacted</option>
              <option value="qualified">qualified</option>
              <option value="lost">lost</option>
              <option value="converted">converted</option>
            </select>
          </Filter>
          <Filter label="Source">
            <select
              value={sourceFilter}
              onChange={(e) => {
                setSourceFilter(e.target.value);
                setPage(0);
              }}
              style={inputStyle}
            >
              <option value="">Все</option>
              {(sources.data ?? []).map((s) => (
                <option key={s} value={s}>
                  {s}
                </option>
              ))}
            </select>
          </Filter>
          <Filter label="Converted">
            <select
              value={convertedFilter}
              onChange={(e) => {
                setConvertedFilter(e.target.value);
                setPage(0);
              }}
              style={inputStyle}
            >
              <option value="">Все</option>
              <option value="true">Да (есть сделка)</option>
              <option value="false">Нет</option>
            </select>
          </Filter>
        </div>
      </section>

      {/* Table */}
      <section style={cardStyle}>
        {leads.isLoading ? (
          <p style={{ color: "#5b6066" }}>Загрузка…</p>
        ) : (leads.data?.rows.length ?? 0) === 0 ? (
          <p style={{ color: "#5b6066" }}>
            Лидов не найдено. Если БД пустая — импортируй данные{" "}
            <code>data/sql/52_import_prinzip_crm.py</code>.
          </p>
        ) : (
          <>
            <div
              style={{
                marginBottom: 12,
                fontSize: 12,
                color: "#5b6066",
                display: "flex",
                justifyContent: "space-between",
              }}
            >
              <span>
                Показано {leads.data?.rows.length ?? 0} из{" "}
                <strong>{leads.data?.total.toLocaleString("ru") ?? 0}</strong>
              </span>
              <span>
                Стр. {page + 1} из{" "}
                {Math.max(1, Math.ceil((leads.data?.total ?? 0) / limit))}
              </span>
            </div>

            <div style={{ overflowX: "auto" }}>
              <table
                style={{
                  width: "100%",
                  borderCollapse: "collapse",
                  fontSize: 13,
                }}
              >
                <thead>
                  <tr style={{ background: "#f6f7f9" }}>
                    {[
                      "Когда",
                      "Имя",
                      "Тел.",
                      "Source",
                      "ЖК",
                      "К-т",
                      "Бюджет",
                      "Статус",
                      "Сделка",
                    ].map((h) => (
                      <th key={h} style={th}>
                        {h}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {(leads.data?.rows ?? []).map((r, i) => (
                    <tr
                      key={r.lead_id}
                      style={{
                        borderBottom: "1px solid #eef0f3",
                        background: i % 2 ? "#fafbfc" : "#fff",
                      }}
                    >
                      <td style={td}>
                        {r.created_at?.slice(0, 10) ?? "—"}
                        <div style={{ fontSize: 11, color: "#73767e" }}>
                          {r.created_at?.slice(11, 16) ?? ""}
                        </div>
                      </td>
                      <td style={td}>{r.name ?? "—"}</td>
                      <td style={{ ...td, fontFamily: "monospace" }}>
                        {r.phone_last4 ? `***${r.phone_last4}` : "—"}
                      </td>
                      <td style={td}>
                        <span
                          style={{
                            background: "#e0e7ff",
                            color: "#3730a3",
                            padding: "2px 6px",
                            borderRadius: 3,
                            fontSize: 11,
                          }}
                        >
                          {r.source ?? "—"}
                        </span>
                      </td>
                      <td style={td}>
                        {r.obj_interest ? (
                          <Link
                            href={`/analytics/objects/${r.obj_interest}`}
                            style={{
                              color: "#1d4ed8",
                              textDecoration: "none",
                              fontSize: 12,
                            }}
                          >
                            {r.obj_name ?? `obj ${r.obj_interest}`}
                          </Link>
                        ) : (
                          "—"
                        )}
                      </td>
                      <td style={td}>{r.rooms ?? "—"}</td>
                      <td style={{ ...td, fontSize: 12 }}>
                        {r.budget_min || r.budget_max
                          ? `${fmtMoney(r.budget_min)}–${fmtMoney(r.budget_max)}`
                          : "—"}
                      </td>
                      <td style={td}>
                        <StatusBadge status={r.status} />
                      </td>
                      <td style={td}>
                        {r.converted ? (
                          <div>
                            <span style={{ color: "#0a7a3a", fontWeight: 600 }}>
                              ✓
                            </span>{" "}
                            {fmtMoney(r.deal_price)}
                            <div style={{ fontSize: 11, color: "#73767e" }}>
                              {r.deal_closed_at?.slice(0, 10) ?? ""}
                            </div>
                          </div>
                        ) : (
                          <span style={{ color: "#9ca3af" }}>—</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            {/* Pagination */}
            <div
              style={{
                display: "flex",
                gap: 8,
                marginTop: 16,
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <button
                onClick={() => setPage((p) => Math.max(0, p - 1))}
                disabled={page === 0}
                style={pageBtn}
              >
                ← Назад
              </button>
              <span style={{ fontSize: 13, color: "#5b6066" }}>
                {page * limit + 1}–
                {Math.min((page + 1) * limit, leads.data?.total ?? 0)}
              </span>
              <button
                onClick={() => setPage((p) => p + 1)}
                disabled={(page + 1) * limit >= (leads.data?.total ?? 0)}
                style={pageBtn}
              >
                Дальше →
              </button>
            </div>
          </>
        )}
      </section>
    </>
  );
}

function Card({
  label,
  value,
  hint,
}: {
  label: string;
  value: string | number;
  hint?: string;
}) {
  return (
    <div
      style={{
        background: "#fff",
        border: "1px solid #e6e8ec",
        borderRadius: 12,
        padding: "16px 18px",
        flex: 1,
        minWidth: 160,
      }}
    >
      <div
        style={{
          fontSize: 12,
          color: "#5b6066",
          textTransform: "uppercase",
          letterSpacing: 0.4,
        }}
      >
        {label}
      </div>
      <div style={{ marginTop: 6, fontSize: 24, fontWeight: 600 }}>{value}</div>
      {hint ? (
        <div style={{ fontSize: 12, color: "#73767e", marginTop: 4 }}>
          {hint}
        </div>
      ) : null}
    </div>
  );
}

function Filter({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      <span
        style={{
          fontSize: 11,
          color: "#5b6066",
          textTransform: "uppercase",
          letterSpacing: 0.4,
        }}
      >
        {label}
      </span>
      {children}
    </label>
  );
}

function StatusBadge({ status }: { status: string | null }) {
  const colors: Record<string, { bg: string; fg: string }> = {
    new: { bg: "#e0e7ff", fg: "#3730a3" },
    contacted: { bg: "#fef3c7", fg: "#92400e" },
    qualified: { bg: "#dbeafe", fg: "#1e40af" },
    lost: { bg: "#fee2e2", fg: "#991b1b" },
    converted: { bg: "#dcfce7", fg: "#065f46" },
  };
  const c = colors[status ?? ""] ?? { bg: "#f3f4f6", fg: "#374151" };
  return (
    <span
      style={{
        background: c.bg,
        color: c.fg,
        fontSize: 11,
        padding: "3px 8px",
        borderRadius: 3,
        fontWeight: 600,
      }}
    >
      {status ?? "—"}
    </span>
  );
}

const inputStyle = {
  padding: "8px 10px",
  border: "1px solid #d1d5db",
  borderRadius: 6,
  fontSize: 13,
  minWidth: 160,
  boxSizing: "border-box" as const,
};
const th = {
  padding: "10px 12px",
  textAlign: "left" as const,
  fontWeight: 600,
  borderBottom: "1px solid #e6e8ec",
  color: "#374151",
};
const td = {
  padding: "10px 12px",
  verticalAlign: "top" as const,
};
const pageBtn = {
  padding: "8px 14px",
  background: "#f3f4f6",
  color: "#1f2937",
  border: "1px solid #d1d5db",
  borderRadius: 6,
  fontSize: 13,
  cursor: "pointer",
};
