"use client";

import { useState, useCallback, useEffect, useMemo } from "react";
import { SearchForm, SearchField } from "@/components/layout/search-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { SearchableCodeSelect } from "@/components/ui/searchable-code-select";
import { numberWithCommas } from "@/lib/utils";
import Swal from "sweetalert2";

interface Product { CODE: string; NAME: string }
interface MonthRow {
  MM: string;
  CONTRACT_CNT_YEAR: number;
  CONTRACT_COST_YEAR_ORG: number;
  CONTRACT_COST_YEAR: number;
  RELEASE_CNT_YEAR: number;
  [key: string]: number | string;
}
interface YearGoal {
  YEAR: string;
  PRICE: number;
  YEAR_GOAL_OBJID?: string;
  CONTRACT_CNT_YEAR: number;
  CONTRACT_COST_YEAR: number;
  GOAL_RATE: number;
}

const PIE_COLORS = ["#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6", "#dd4477", "#66aa00"];

// 간단한 SVG 파이 차트
function PieChart({ data, size = 220 }: { data: { label: string; value: number }[]; size?: number }) {
  const total = data.reduce((s, d) => s + d.value, 0);
  if (total === 0) {
    return <div className="text-center text-xs text-gray-400 py-10">데이터 없음</div>;
  }
  const cx = size / 2, cy = size / 2, r = size / 2 - 4;
  let acc = 0;
  const slices = data.map((d, i) => {
    const start = (acc / total) * Math.PI * 2 - Math.PI / 2;
    acc += d.value;
    const end = (acc / total) * Math.PI * 2 - Math.PI / 2;
    const large = end - start > Math.PI ? 1 : 0;
    const x1 = cx + r * Math.cos(start);
    const y1 = cy + r * Math.sin(start);
    const x2 = cx + r * Math.cos(end);
    const y2 = cy + r * Math.sin(end);
    const mid = (start + end) / 2;
    const lx = cx + r * 0.65 * Math.cos(mid);
    const ly = cy + r * 0.65 * Math.sin(mid);
    const pct = ((d.value / total) * 100);
    return {
      path: `M ${cx} ${cy} L ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2} Z`,
      color: PIE_COLORS[i % PIE_COLORS.length],
      label: d.label,
      value: d.value,
      pct,
      lx, ly,
    };
  });

  return (
    <div className="flex items-start gap-3">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        {slices.map((s, i) => (
          <g key={i}>
            <path d={s.path} fill={s.color} stroke="#fff" strokeWidth="1" />
            {s.pct >= 5 && (
              <text x={s.lx} y={s.ly} fontSize="10" fill="#fff" textAnchor="middle" dominantBaseline="middle">
                {s.pct.toFixed(0)}%
              </text>
            )}
          </g>
        ))}
      </svg>
      <div className="text-[11px] flex flex-col gap-0.5 pt-2 min-w-0">
        {slices.map((s, i) => (
          <div key={i} className="flex items-center gap-1">
            <span className="inline-block w-3 h-3 shrink-0 rounded-sm" style={{ backgroundColor: s.color }} />
            <span className="truncate">{s.label}</span>
            <span className="text-gray-500 ml-auto pl-1 shrink-0">{s.value}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// 년도별 영업현황 — 막대 2개(목표/수주) + 꺾은선(달성율)
function GoalComboChart({ years }: { years: YearGoal[] }) {
  const W = 340, H = 230, PAD_L = 36, PAD_R = 36, PAD_T = 16, PAD_B = 34;
  const maxPrice = Math.max(1, ...years.flatMap((y) => [y.PRICE, y.CONTRACT_COST_YEAR]));
  const maxRate = Math.max(100, ...years.map((y) => y.GOAL_RATE));
  const chartW = W - PAD_L - PAD_R;
  const chartH = H - PAD_T - PAD_B;
  const xStep = chartW / years.length;
  const barW = Math.min(18, xStep / 3);

  return (
    <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`}>
      {/* Y축 가이드 */}
      <line x1={PAD_L} y1={PAD_T} x2={PAD_L} y2={H - PAD_B} stroke="#ddd" />
      <line x1={PAD_L} y1={H - PAD_B} x2={W - PAD_R} y2={H - PAD_B} stroke="#ddd" />

      {years.map((y, i) => {
        const cx = PAD_L + xStep * (i + 0.5);
        const hGoal = (y.PRICE / maxPrice) * chartH;
        const hActual = (y.CONTRACT_COST_YEAR / maxPrice) * chartH;
        const rateY = H - PAD_B - (y.GOAL_RATE / maxRate) * chartH;
        return (
          <g key={i}>
            <rect x={cx - barW - 1} y={H - PAD_B - hGoal} width={barW} height={hGoal} fill="#3366cc" />
            <rect x={cx + 1} y={H - PAD_B - hActual} width={barW} height={hActual} fill="#dc3912" />
            <text x={cx} y={H - PAD_B + 14} fontSize="11" textAnchor="middle" fill="#444">{y.YEAR}</text>
            <circle cx={cx} cy={rateY} r={3} fill="#ff9900" stroke="#fff" strokeWidth="1" />
            <text x={cx} y={rateY - 6} fontSize="9" textAnchor="middle" fill="#b87a00">{y.GOAL_RATE.toFixed(0)}%</text>
            {i > 0 && (() => {
              const prev = years[i - 1];
              const pcx = PAD_L + xStep * (i - 1 + 0.5);
              const prateY = H - PAD_B - (prev.GOAL_RATE / maxRate) * chartH;
              return <line x1={pcx} y1={prateY} x2={cx} y2={rateY} stroke="#ff9900" strokeWidth="1.5" />;
            })()}
          </g>
        );
      })}

      {/* 범례 */}
      <g transform={`translate(${PAD_L},${PAD_T - 8})`}>
        <rect x="0" y="0" width="10" height="10" fill="#3366cc" />
        <text x="14" y="9" fontSize="10" fill="#333">영업목표(억)</text>
        <rect x="85" y="0" width="10" height="10" fill="#dc3912" />
        <text x="99" y="9" fontSize="10" fill="#333">수주(억)</text>
        <line x1="165" y1="5" x2="180" y2="5" stroke="#ff9900" strokeWidth="2" />
        <circle cx="172" cy="5" r="3" fill="#ff9900" />
        <text x="184" y="9" fontSize="10" fill="#333">달성율(%)</text>
      </g>
    </svg>
  );
}

export default function ContractDashboardPage() {
  const currentYear = new Date().getFullYear();
  const [year, setYear] = useState(String(currentYear));
  const [categoryCd, setCategoryCd] = useState("");
  const [customerObjid, setCustomerObjid] = useState("");
  const [product, setProduct] = useState("");

  const [products, setProducts] = useState<Product[]>([]);
  const [total, setTotal] = useState<MonthRow | null>(null);
  const [months, setMonths] = useState<MonthRow[]>([]);
  const [years, setYears] = useState<YearGoal[]>([]);
  const [customerStats, setCustomerStats] = useState<{ OBJID: string; SUPPLY_NAME: string; TOTAL_SUPPLY_UNIT_CNT: number }[]>([]);
  const [customers, setCustomers] = useState<{ value: string; label: string }[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetch("/api/sales/customer", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" })
      .then((r) => r.json()).then((d) => setCustomers((d.RESULTLIST || []).map((r: Record<string, unknown>) => ({
        value: String(r.OBJID || ""), label: String(r.SUPPLY_NAME || ""),
      })))).catch(() => {});
  }, []);

  const fetchAll = useCallback(async () => {
    setLoading(true);
    try {
      const body = { Year: year, category_cd: categoryCd, customer_objid: customerObjid, product };
      const [dashR, goalR, custR] = await Promise.all([
        fetch("/api/sales/contract-dashboard", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }),
        fetch("/api/sales/contract-dashboard/year-goal", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ Year: year }) }),
        fetch("/api/sales/contract-dashboard/customer-stats", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ Year: year }) }),
      ]);
      if (dashR.ok) {
        const d = await dashR.json();
        setProducts(d.products || []);
        setTotal(d.total || null);
        setMonths(d.months || []);
      }
      if (goalR.ok) {
        const g = await goalR.json();
        const ys = (g.years || []) as Record<string, unknown>[];
        setYears(ys.map((y) => ({
          YEAR: String(y.YEAR || ""),
          PRICE: Number(y.PRICE || 0),
          YEAR_GOAL_OBJID: String(y.YEAR_GOAL_OBJID || ""),
          CONTRACT_CNT_YEAR: Number(y.CONTRACT_CNT_YEAR || 0),
          CONTRACT_COST_YEAR: Number(y.CONTRACT_COST_YEAR || 0),
          GOAL_RATE: Number(y.GOAL_RATE || 0),
        })));
      }
      if (custR.ok) {
        const c = await custR.json();
        setCustomerStats(((c.rows || []) as Record<string, unknown>[]).map((r) => ({
          OBJID: String(r.OBJID || ""),
          SUPPLY_NAME: String(r.SUPPLY_NAME || ""),
          TOTAL_SUPPLY_UNIT_CNT: Number(r.TOTAL_SUPPLY_UNIT_CNT || 0),
        })));
      }
    } finally {
      setLoading(false);
    }
  }, [year, categoryCd, customerObjid, product]);

  useEffect(() => { fetchAll(); }, [fetchAll]);

  // 제품별 연 합계 (파이 데이터)
  const productPieData = useMemo(() => {
    if (!total) return [];
    return products.map((p) => ({
      label: p.NAME,
      value: Number(total[`CONTRACT_CNT_MONTH_${p.CODE}`] || 0),
    })).filter((d) => d.value > 0);
  }, [products, total]);

  const customerPieData = useMemo(() => customerStats.map((c) => ({
    label: c.SUPPLY_NAME, value: c.TOTAL_SUPPLY_UNIT_CNT,
  })), [customerStats]);

  const handleRegistGoal = async () => {
    const current = years.find((y) => y.YEAR === year);
    const { value: priceStr } = await Swal.fire<string>({
      title: `${year}년 영업목표`,
      input: "number",
      inputLabel: "영업목표 (억원)",
      inputValue: String(current?.PRICE || ""),
      showCancelButton: true,
      confirmButtonText: "저장",
      cancelButtonText: "취소",
    });
    if (!priceStr) return;
    const res = await fetch("/api/sales/contract-dashboard/year-goal/save", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ Year: year, PRICE: priceStr, YEAR_GOAL_OBJID: current?.YEAR_GOAL_OBJID || "" }),
    });
    const j = await res.json();
    if (j.success) {
      Swal.fire({ icon: "success", title: "저장되었습니다.", timer: 1200, showConfirmButton: false });
      fetchAll();
    } else {
      Swal.fire("오류", j.message || "저장 실패", "error");
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-800">영업관리_계약현황</h2>
        <div className="flex gap-2">
          <Button size="sm" onClick={handleRegistGoal}>영업목표등록</Button>
          <Button size="sm" variant="secondary" onClick={fetchAll}>조회</Button>
        </div>
      </div>

      <SearchForm onSearch={fetchAll}>
        <SearchField label="년도">
          <select value={year} onChange={(e) => setYear(e.target.value)}
            className="h-9 w-[100px] rounded border border-gray-300 bg-white px-2 text-sm">
            {Array.from({ length: 5 }, (_, i) => currentYear - i).map((y) => (
              <option key={y} value={y}>{y}</option>
            ))}
          </select>
        </SearchField>
        <SearchField label="구분">
          <SearchableCodeSelect codeId="0000167" value={categoryCd} onChange={setCategoryCd} className="w-[140px]" />
        </SearchField>
        <SearchField label="고객사">
          <select value={customerObjid} onChange={(e) => setCustomerObjid(e.target.value)}
            className="h-9 w-[180px] rounded border border-gray-300 bg-white px-2 text-sm">
            <option value="">전체</option>
            {customers.map((c) => <option key={c.value} value={c.value}>{c.label}</option>)}
          </select>
        </SearchField>
        <SearchField label="제품구분">
          <SearchableCodeSelect codeId="0000001" value={product} onChange={setProduct} className="w-[130px]" />
        </SearchField>
      </SearchForm>

      {loading && <div className="text-xs text-gray-400 mb-2">조회 중...</div>}

      <div className="grid grid-cols-12 gap-3">
        {/* 좌: 계약현황 테이블 */}
        <section className="col-span-12 lg:col-span-5 bg-white border rounded p-2">
          <div className="text-sm font-bold text-gray-700 mb-2 pb-1 border-b">■ 계약현황 ({year})</div>
          <div className="overflow-auto" style={{ maxHeight: "calc(100vh - 330px)" }}>
            <table className="w-full text-[11px] border-collapse">
              <thead className="bg-gray-50 sticky top-0">
                <tr className="border-b">
                  <th className="p-1 border" rowSpan={2}></th>
                  <th className="p-1 border text-center" colSpan={products.length}>수주확정 건수</th>
                  <th className="p-1 border text-center" rowSpan={2}>매출액<br />(억원)</th>
                  <th className="p-1 border text-center" rowSpan={2}>출고</th>
                </tr>
                <tr className="border-b">
                  {products.map((p) => <th key={p.CODE} className="p-1 border text-center">{p.NAME}</th>)}
                </tr>
              </thead>
              <tbody>
                {total && (
                  <tr className="bg-orange-50 font-semibold">
                    <td className="p-1 border text-center">계</td>
                    {products.map((p) => (
                      <td key={p.CODE} className="p-1 border text-right">
                        {numberWithCommas(Number(total[`CONTRACT_CNT_MONTH_${p.CODE}`] || 0))}
                      </td>
                    ))}
                    <td className="p-1 border text-right">{(total.CONTRACT_COST_YEAR || 0).toFixed(2)}</td>
                    <td className="p-1 border text-right">{numberWithCommas(total.RELEASE_CNT_YEAR || 0)}</td>
                  </tr>
                )}
                {months.map((m) => (
                  <tr key={m.MM} className="hover:bg-gray-50">
                    <td className="p-1 border text-center">{parseInt(m.MM, 10)}월</td>
                    {products.map((p) => (
                      <td key={p.CODE} className="p-1 border text-right">
                        {Number(m[`CONTRACT_CNT_MONTH_${p.CODE}`] || 0) > 0
                          ? numberWithCommas(Number(m[`CONTRACT_CNT_MONTH_${p.CODE}`] || 0))
                          : ""}
                      </td>
                    ))}
                    <td className="p-1 border text-right">{m.CONTRACT_COST_YEAR ? m.CONTRACT_COST_YEAR.toFixed(2) : ""}</td>
                    <td className="p-1 border text-right">{m.RELEASE_CNT_YEAR > 0 ? numberWithCommas(m.RELEASE_CNT_YEAR) : ""}</td>
                  </tr>
                ))}
                {(!months || months.length === 0) && (
                  <tr><td colSpan={products.length + 3} className="p-4 text-center text-gray-400">데이터 없음</td></tr>
                )}
              </tbody>
            </table>
          </div>
        </section>

        {/* 중: 영업목표 테이블 + 제품별현황 파이 */}
        <section className="col-span-12 lg:col-span-3 flex flex-col gap-3">
          <div className="bg-white border rounded p-2">
            <div className="text-sm font-bold text-gray-700 mb-2 pb-1 border-b">■ 영업목표</div>
            <table className="w-full text-[11px] border-collapse">
              <thead className="bg-gray-50">
                <tr className="border-b">
                  <th className="p-1 border" rowSpan={2}>년도</th>
                  <th className="p-1 border" rowSpan={2}>영업목표<br />(억원)</th>
                  <th className="p-1 border" colSpan={3}>현황</th>
                </tr>
                <tr className="border-b">
                  <th className="p-1 border">계약건수</th>
                  <th className="p-1 border">계약금액</th>
                  <th className="p-1 border">달성율</th>
                </tr>
              </thead>
              <tbody>
                {years.length === 0 ? (
                  <tr><td colSpan={5} className="p-3 text-center text-gray-400">데이터 없음</td></tr>
                ) : (
                  years.slice().reverse().map((y) => (
                    <tr key={y.YEAR} className="hover:bg-gray-50">
                      <td className="p-1 border text-center">{y.YEAR}</td>
                      <td className="p-1 border text-right">{numberWithCommas(y.PRICE)}</td>
                      <td className="p-1 border text-right">{numberWithCommas(y.CONTRACT_CNT_YEAR)}</td>
                      <td className="p-1 border text-right">{(y.CONTRACT_COST_YEAR || 0).toFixed(2)}</td>
                      <td className="p-1 border text-right">{(y.GOAL_RATE || 0).toFixed(1)}%</td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          <div className="bg-white border rounded p-2 flex-1">
            <div className="text-sm font-bold text-gray-700 mb-2 pb-1 border-b">■ 제품별현황</div>
            <PieChart data={productPieData} />
          </div>
        </section>

        {/* 우: 년도별 영업현황 + 고객사별현황 */}
        <section className="col-span-12 lg:col-span-4 flex flex-col gap-3">
          <div className="bg-white border rounded p-2">
            <div className="text-sm font-bold text-gray-700 mb-2 pb-1 border-b">■ 년도별 영업현황</div>
            <GoalComboChart years={years} />
          </div>

          <div className="bg-white border rounded p-2 flex-1">
            <div className="text-sm font-bold text-gray-700 mb-2 pb-1 border-b">■ 고객사별현황</div>
            <PieChart data={customerPieData} />
          </div>
        </section>
      </div>
    </div>
  );
}
