"use client";

import { useEffect, useState } from "react";
import {
  PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend,
  ComposedChart, Bar, Line, XAxis, YAxis, CartesianGrid,
} from "recharts";
import { useAuthStore } from "@/store/auth-store";
import { useMenuStore } from "@/store/menu-store";
import { numberWithCommas } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
  FolderKanban, AlertCircle,
  TrendingUp, BarChart3, Briefcase,
} from "lucide-react";

interface YearGoalRow {
  YEAR: string;
  CONTRACT_CNT_YEAR_IN?: number;
  CONTRACT_CNT_YEAR_OUT?: number;
  CONTRACT_CNT_YEAR_RATE?: number;
  CONTRACT_COST_YEAR?: string | number;
  PRICE?: string | number;
  GOAL_RATE?: number;
  YEAR_GOAL_OBJID?: string;
}

interface DashboardData {
  projectStats: {
    CNT_TOTAL?: number; CNT_NOPLAN?: number; CNT_ING?: number;
    CNT_DELAY?: number; CNT_END?: number;
    ISSUE_TOTAL?: number; ISSUE_MISS?: number;
  };
  productDist: { CODE: string; NAME: string; CNT: number }[];
  supplyDist: { CODE: string; NAME: string; CNT: number }[];
  monthlyContract: { MONTH: number; AMOUNT: string }[];
  projectList: Record<string, unknown>[];
  yearGoalInfo: YearGoalRow[];
}

type Tab = "sales" | "project";

const PIE_COLORS = ["#3b82f6", "#22c55e", "#a855f7", "#f97316", "#ef4444", "#14b8a6", "#eab308"];

export default function DashboardPage() {
  const { user } = useAuthStore();
  const { topMenus, fetchSideMenus } = useMenuStore();
  const [data, setData] = useState<DashboardData | null>(null);
  const [year, setYear] = useState(new Date().getFullYear().toString());
  const [tab, setTab] = useState<Tab>("sales");

  useEffect(() => {
    if (topMenus.length > 0) {
      const userMenu = topMenus.find((m) => m.MENU_NAME_KOR !== "관리자") || topMenus[0];
      fetchSideMenus(userMenu.OBJID);
    }
  }, [topMenus, fetchSideMenus]);

  useEffect(() => {
    fetch("/api/dashboard", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ year }),
    })
      .then((r) => r.ok ? r.json() : null)
      .then((d) => setData(d))
      .catch(() => {});
  }, [year]);

  return (
    <div className="flex flex-col h-[calc(100vh-120px)]">
      {/* 헤더 */}
      <div className="flex items-center justify-between mb-6 shrink-0">
        <h1 className="text-xl font-bold text-gray-800">
          Dashboard
          <span className="text-sm font-normal text-gray-400 ml-2">
            {user?.userName}님, 환영합니다.
          </span>
        </h1>
        <div className="flex items-center gap-3">
          {/* 탭 */}
          <div className="inline-flex bg-gray-100 rounded-lg p-1">
            <TabButton active={tab === "sales"} onClick={() => setTab("sales")} icon={TrendingUp} label="영업" />
            <TabButton active={tab === "project"} onClick={() => setTab("project")} icon={Briefcase} label="프로젝트" />
          </div>
          <select
            value={year}
            onChange={(e) => setYear(e.target.value)}
            className="h-9 rounded border border-gray-300 bg-white px-3 text-sm"
          >
            {Array.from({ length: 5 }, (_, i) => new Date().getFullYear() - i).map((y) => (
              <option key={y} value={y}>{y}년</option>
            ))}
          </select>
        </div>
      </div>

      {/* 탭 내용 — 남은 공간 가득 채움 */}
      <div className="flex-1 min-h-0">
        {tab === "sales" ? (
          <SalesTab data={data} year={year} />
        ) : (
          <ProjectTab data={data} year={year} />
        )}
      </div>
    </div>
  );
}

function TabButton({ active, onClick, icon: Icon, label }: {
  active: boolean; onClick: () => void; icon: React.ElementType; label: string;
}) {
  return (
    <button
      onClick={onClick}
      className={`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-colors ${
        active ? "bg-white text-primary shadow-sm" : "text-gray-500 hover:text-gray-700"
      }`}
    >
      <Icon size={15} />
      {label}
    </button>
  );
}

function SalesTab({ data, year }: { data: DashboardData | null; year: string }) {
  const openGoalPopup = () => {
    const w = 700, h = 500;
    const left = (window.screen.width - w) / 2;
    const top = (window.screen.height - h) / 2;
    window.open(`/sales/year-goal?year=${year}`, "yearGoalPopup",
      `width=${w},height=${h},left=${left},top=${top},menubars=no,scrollbars=yes,resizable=yes`);
  };

  return (
    <div className="flex flex-col gap-4 h-full min-h-0">
      {/* 상단: 영업현황 표 (고정 높이) */}
      <YearGoalTable info={data?.yearGoalInfo || []} onOpenGoal={openGoalPopup} />

      {/* 하단: 3분할 — 제품별 pie / 고객사별 pie / 년도별 combo (남은 공간 가득) */}
      <div className="grid grid-cols-3 gap-4 flex-1 min-h-0">
        <PieCard title="■ 제품별현황" data={data?.productDist || []} />
        <PieCard title="■ 고객사별현황" data={data?.supplyDist || []} />
        <YearSalesComboChart info={data?.yearGoalInfo || []} />
      </div>
    </div>
  );
}

function YearGoalTable({ info, onOpenGoal }: { info: YearGoalRow[]; onOpenGoal: () => void }) {
  return (
    <div className="bg-white rounded-xl border border-gray-200 p-4 shadow-sm shrink-0">
      <div className="flex items-center justify-between mb-3">
        <h3 className="text-sm font-semibold text-gray-700 flex items-center gap-2">
          <TrendingUp size={16} className="text-primary" />
          영업현황
        </h3>
        <Button size="sm" onClick={onOpenGoal}>영업목표 등록</Button>
      </div>
      <table className="w-full text-xs border-collapse">
        <thead>
          <tr className="bg-gray-600 text-white">
            <th rowSpan={2} className="border border-gray-300 px-2 py-1 font-semibold">년도</th>
            <th colSpan={2} className="border border-gray-300 px-2 py-1 font-semibold">수주현황(건수)</th>
            <th rowSpan={2} className="border border-gray-300 px-2 py-1 font-semibold">수주율(%)</th>
            <th rowSpan={2} className="border border-gray-300 px-2 py-1 font-semibold">예상매출(억원)</th>
            <th rowSpan={2} className="border border-gray-300 px-2 py-1 font-semibold">영업목표(억원)</th>
            <th rowSpan={2} className="border border-gray-300 px-2 py-1 font-semibold">달성율(%)</th>
          </tr>
          <tr className="bg-gray-600 text-white">
            <th className="border border-gray-300 px-2 py-1 font-semibold">국내</th>
            <th className="border border-gray-300 px-2 py-1 font-semibold">해외</th>
          </tr>
        </thead>
        <tbody>
          {info.length === 0 ? (
            <tr><td colSpan={7} className="text-center py-4 text-gray-400">데이터가 없습니다.</td></tr>
          ) : info.map((row, idx) => (
            <tr key={idx} className="hover:bg-gray-50">
              <td className="border border-gray-200 px-2 py-1.5 text-center font-medium">{row.YEAR}</td>
              <td className="border border-gray-200 px-2 py-1.5 text-center">{row.CONTRACT_CNT_YEAR_IN ?? 0}</td>
              <td className="border border-gray-200 px-2 py-1.5 text-center">{row.CONTRACT_CNT_YEAR_OUT ?? 0}</td>
              <td className="border border-gray-200 px-2 py-1.5 text-center">{row.CONTRACT_CNT_YEAR_RATE ?? 0}</td>
              <td className="border border-gray-200 px-2 py-1.5 text-center">{numberWithCommas(Number(row.CONTRACT_COST_YEAR ?? 0))}</td>
              <td className="border border-gray-200 px-2 py-1.5 text-center">{numberWithCommas(Number(row.PRICE ?? 0))}</td>
              <td className="border border-gray-200 px-2 py-1.5 text-center">{row.GOAL_RATE ?? 0}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function PieCard({ title, data }: { title: string; data: { CODE: string; NAME: string; CNT: number }[] }) {
  const chartData = data.map((d, i) => ({
    name: d.NAME || `코드 ${d.CODE}`,
    value: d.CNT,
    color: PIE_COLORS[i % PIE_COLORS.length],
  }));
  const total = chartData.reduce((s, d) => s + d.value, 0);

  return (
    <div className="bg-white rounded-xl border border-gray-200 p-5 shadow-sm flex flex-col min-h-0">
      <h3 className="text-sm font-semibold text-gray-700 mb-3 shrink-0">{title}</h3>
      {total === 0 ? (
        <div className="flex-1 flex items-center justify-center text-sm text-gray-400">데이터가 없습니다.</div>
      ) : (
        <div className="flex-1 min-h-0">
          <ResponsiveContainer width="100%" height="100%">
            <PieChart>
              <Pie
                data={chartData}
                dataKey="value"
                nameKey="name"
                cx="50%"
                cy="50%"
                outerRadius="75%"
                label={({ percent }: { percent?: number }) =>
                  percent != null && percent >= 0.05 ? `${Math.round(percent * 100)}%` : ""
                }
                labelLine={false}
              >
                {chartData.map((entry, index) => (
                  <Cell key={`cell-${index}`} fill={entry.color} />
                ))}
              </Pie>
              <Tooltip formatter={(v) => `${v}건`} />
              <Legend
                verticalAlign="bottom"
                align="center"
                iconSize={10}
                wrapperStyle={{ fontSize: "11px" }}
              />
            </PieChart>
          </ResponsiveContainer>
        </div>
      )}
    </div>
  );
}

function YearSalesComboChart({ info }: { info: YearGoalRow[] }) {
  // 과거→현재 순서
  const chartData = [...info]
    .sort((a, b) => Number(a.YEAR) - Number(b.YEAR))
    .map((r) => ({
      YEAR: r.YEAR,
      영업목표: Number(r.PRICE || 0),
      수주금액: Number(r.CONTRACT_COST_YEAR || 0),
      달성율: Number(r.GOAL_RATE || 0),
    }));

  return (
    <div className="bg-white rounded-xl border border-gray-200 p-5 shadow-sm flex flex-col min-h-0">
      <h3 className="text-sm font-semibold text-gray-700 mb-3 shrink-0">■ 년도별 영업현황</h3>
      <div className="flex-1 min-h-0">
        <ResponsiveContainer width="100%" height="100%">
          <ComposedChart data={chartData} margin={{ top: 5, right: 10, left: 0, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="#f1f1f1" />
            <XAxis dataKey="YEAR" tick={{ fontSize: 11 }} />
            <YAxis yAxisId="left" tick={{ fontSize: 10 }} />
            <YAxis yAxisId="right" orientation="right" tick={{ fontSize: 10 }} unit="%" />
            <Tooltip
              formatter={(v, name) =>
                name === "달성율" ? `${v}%` : `${numberWithCommas(Number(v))}억`
              }
            />
            <Legend wrapperStyle={{ fontSize: "11px" }} iconSize={10} />
            <Bar yAxisId="left" dataKey="영업목표" fill="#3b82f6" barSize={20} />
            <Bar yAxisId="left" dataKey="수주금액" fill="#ef4444" barSize={20} />
            <Line yAxisId="right" type="monotone" dataKey="달성율" stroke="#f97316" strokeWidth={2}
              dot={{ r: 5, fill: "#f97316", stroke: "#fff", strokeWidth: 2 }} />
          </ComposedChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

type StatusFilter = "all" | "noplan" | "ing" | "delay" | "end";

const FILTER_LABELS: Record<StatusFilter, string> = {
  all: "전체",
  noplan: "계획미수립",
  ing: "진행중",
  delay: "지연",
  end: "종료",
};

function ProjectTab({ data, year }: { data: DashboardData | null; year: string }) {
  const stats = data?.projectStats || {};
  const allProjects = (data?.projectList || []) as Record<string, unknown>[];
  const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
  const [projectFilter, setProjectFilter] = useState<string>("");
  const [selectedIdx, setSelectedIdx] = useState(0);

  const projectList = allProjects.filter((p) => {
    const s = String(p.STATUS_TITLE || "");
    if (statusFilter !== "all") {
      if (statusFilter === "noplan" && s !== "계획미수립") return false;
      if (statusFilter === "ing" && s !== "진행중") return false;
      if (statusFilter === "delay" && s !== "지연") return false;
      if (statusFilter === "end" && s !== "종료") return false;
    }
    if (projectFilter && String(p.OBJID) !== projectFilter) return false;
    return true;
  });
  const selected = projectList[selectedIdx] || projectList[0];

  const toggleFilter = (f: StatusFilter) => {
    setSelectedIdx(0);
    setStatusFilter((cur) => (cur === f ? "all" : f));
  };

  const openProjectSchedule = () => {
    // 프로젝트 일정 전체 보기 → 프로젝트 관리 > 종합현황 페이지로 이동
    window.location.href = `/project/total?year=${year}`;
  };

  return (
    <div className="flex flex-col gap-5 h-full">
      {/* 상단 프로젝트현황 카드 — 원본 스타일 (5개 숫자 가로 + 컨트롤) */}
      <div className="bg-white rounded-xl border border-gray-200 p-5 shadow-sm shrink-0">
        <div className="flex items-center justify-between mb-3">
          <h3 className="text-sm font-semibold text-gray-700 flex items-center gap-2">
            <FolderKanban size={16} className="text-primary" />
            프로젝트현황
          </h3>
          <Button size="sm" onClick={openProjectSchedule}>프로젝트 일정 전체 보기</Button>
        </div>
        <div className="flex items-start gap-4">
          {/* 좌측: 년도/프로젝트번호 셀렉트 */}
          <div className="flex flex-col gap-2 min-w-[240px] pr-4 border-r border-gray-100">
            <div className="flex items-center gap-2">
              <label className="text-xs text-gray-500 w-20">년도</label>
              <div className="flex-1 text-sm font-medium">{year}</div>
            </div>
            <div className="flex items-center gap-2">
              <label className="text-xs text-gray-500 w-20">프로젝트번호</label>
              <select value={projectFilter} onChange={(e) => setProjectFilter(e.target.value)}
                className="flex-1 h-8 rounded border border-gray-300 bg-white px-2 text-xs">
                <option value="">선택</option>
                {allProjects.map((p) => (
                  <option key={String(p.OBJID)} value={String(p.OBJID)}>{String(p.PROJECT_NO || "")}</option>
                ))}
              </select>
            </div>
          </div>
          {/* 우측: 5개 숫자 가로 배치 */}
          <div className="flex-1 grid grid-cols-5 gap-2">
            <CountBadge label="전체" value={Number(stats.CNT_TOTAL || 0)} color="blue"
              active={statusFilter === "all"} onClick={() => setStatusFilter("all")} />
            <CountBadge label="계획미수립" value={Number(stats.CNT_NOPLAN || 0)} color="blue"
              active={statusFilter === "noplan"} onClick={() => toggleFilter("noplan")} />
            <CountBadge label="진행중" value={Number(stats.CNT_ING || 0)} color="blue"
              active={statusFilter === "ing"} onClick={() => toggleFilter("ing")} />
            <CountBadge label="지연" value={Number(stats.CNT_DELAY || 0)} color="red"
              active={statusFilter === "delay"} onClick={() => toggleFilter("delay")} />
            <CountBadge label="종료" value={Number(stats.CNT_END || 0)} color="blue"
              active={statusFilter === "end"} onClick={() => toggleFilter("end")} />
          </div>
        </div>
      </div>

      {/* 프로젝트 리스트 — 전체 너비, 원본 10컬럼 구조 */}
      <div className="flex-1 bg-white rounded-xl border border-gray-200 p-4 flex flex-col min-h-0 shadow-sm">
        <h3 className="text-sm font-semibold text-gray-700 mb-3 shrink-0 flex items-center gap-2">
          <FolderKanban size={16} className="text-primary" />
          프로젝트 리스트 {statusFilter !== "all" && (
            <span className="text-xs font-normal text-primary">[{FILTER_LABELS[statusFilter]}]</span>
          )} · 총 {projectList.length}건
          {statusFilter !== "all" && (
            <button onClick={() => setStatusFilter("all")}
              className="ml-auto text-[10px] text-gray-400 hover:text-gray-700">
              필터 해제 ×
            </button>
          )}
        </h3>
        <div className="flex-1 overflow-auto min-h-0 border border-gray-100 rounded">
          <table className="w-full text-sm border-collapse">
            <thead className="sticky top-0 bg-gray-600 text-white z-10">
              <tr>
                <th className="px-2 py-2 font-semibold text-xs w-12">선택</th>
                <th className="px-2 py-2 font-semibold text-xs">고객사</th>
                <th className="px-2 py-2 font-semibold text-xs">제품구분</th>
                <th className="px-2 py-2 font-semibold text-xs">프로젝트번호</th>
                <th className="px-2 py-2 font-semibold text-xs">납기일</th>
                <th className="px-2 py-2 font-semibold text-xs">셋업지</th>
                <th className="px-2 py-2 font-semibold text-xs">제작공장</th>
                <th className="px-2 py-2 font-semibold text-xs">진척율(%)</th>
                <th className="px-2 py-2 font-semibold text-xs">셋업완료일</th>
                <th className="px-2 py-2 font-semibold text-xs">상태</th>
              </tr>
            </thead>
            <tbody>
              {projectList.length === 0 ? (
                <tr><td colSpan={10} className="text-center py-10 text-gray-400">데이터가 없습니다.</td></tr>
              ) : projectList.map((pjt, idx) => {
                const statusTitle = String(pjt.STATUS_TITLE || "");
                const statusColor =
                  statusTitle === "종료" ? "text-green-600" :
                  statusTitle === "지연" ? "text-red-500" :
                  statusTitle === "계획미수립" ? "text-gray-500" :
                  "text-blue-600";
                const isSelected = idx === selectedIdx;
                return (
                  <tr key={idx}
                    className={`border-b border-gray-100 cursor-pointer ${isSelected ? "bg-primary/10" : "hover:bg-gray-50"}`}
                    onClick={() => setSelectedIdx(idx)}>
                    <td className="px-2 py-2 text-center">
                      <input type="radio" checked={isSelected} onChange={() => setSelectedIdx(idx)} className="pointer-events-none" />
                    </td>
                    <td className="px-2 py-2 text-center text-xs">{String(pjt.CUSTOMER_NAME || "")}</td>
                    <td className="px-2 py-2 text-center text-xs">{String(pjt.PRODUCT_NAME || "")}</td>
                    <td className="px-2 py-2 text-center">
                      <span className="inline-block px-2 py-0.5 bg-gray-700 text-white rounded text-[11px]">{String(pjt.PROJECT_NO || "")}</span>
                    </td>
                    <td className="px-2 py-2 text-center text-xs">{String(pjt.CONTRACT_DEL_DATE || "-")}</td>
                    <td className="px-2 py-2 text-center text-xs">{String(pjt.SETUP || "")}</td>
                    <td className="px-2 py-2 text-center text-xs">{String(pjt.MANUFACTURE_PLANT_NAME || "")}</td>
                    <td className="px-2 py-2 text-right text-xs">{Number(pjt.SETUP_RATE || 0).toFixed(1)}</td>
                    <td className="px-2 py-2 text-center text-xs">{String(pjt.SETUP_DONE_DATE || "")}</td>
                    <td className={`px-2 py-2 text-center text-xs font-semibold ${statusColor}`}>{statusTitle}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      {/* 선택된 프로젝트 상세 (이슈 + 투입원가) */}
      <div className="shrink-0">
        <ProjectDetailPanel project={selected} />
      </div>
    </div>
  );
}

function ProjectDetailPanel({ project }: { project: Record<string, unknown> | undefined }) {
  if (!project) {
    return (
      <div className="flex-1 bg-white rounded-xl border border-gray-200 p-10 flex items-center justify-center shadow-sm">
        <div className="text-sm text-gray-400">프로젝트를 선택하세요</div>
      </div>
    );
  }

  const issueTotal = Number(project.ISSUE_CNT || 0);
  const issueDone = Number(project.ISSUE_DONE_CNT || 0);
  const issueMiss = Number(project.ISSUE_MISS_CNT || 0);
  const issueRate = issueTotal > 0 ? Math.round((issueDone / issueTotal) * 100) : 0;

  // 투입원가 항목별 (원본 dashboard.jsp fn_getProjectCostStatusList 이식)
  const contractPrice = Number(project.CONTRACT_PRICE || 0);
  const materialGoal = Number(project.MATERIAL_COST_GOAL || 0);
  const materialActual = Number(project.ACCRUAL_MATERIAL_COST || 0);
  const laborGoal = Number(project.LABOR_COST_GOAL || 0);
  const laborActual = Number(project.LABOR_COST_ACTUAL || 0);
  const expenseGoal = Number(project.EXPENSE_COST_GOAL || 0);
  const expenseActual = Number(project.ACCRUAL_EXPENSE || 0);
  const totalGoalBase = materialGoal + laborGoal + expenseGoal;
  const totalActualBase = materialActual + laborActual + expenseActual;
  // 관리비 = 전체의 10%
  const mgmtGoal = Math.round(totalGoalBase * 0.1);
  const mgmtActual = Math.round(totalActualBase * 0.1);
  const totalGoal = totalGoalBase + mgmtGoal;
  const totalActual = totalActualBase + mgmtActual;
  // 각 항목 투입율(%) — 재료비는 수주가 기준, 나머지는 목표 기준 (원본 로직)
  const materialRate = contractPrice > 0 ? Math.round((materialActual / contractPrice) * 1000) / 10 : 0;
  const laborRate = laborGoal > 0 ? Math.round((laborActual / laborGoal) * 1000) / 10 : 0;
  const expenseRate = expenseGoal > 0 ? Math.round((expenseActual / expenseGoal) * 1000) / 10 : 0;
  const mgmtRate = mgmtGoal > 0 ? Math.round((mgmtActual / mgmtGoal) * 1000) / 10 : 0;
  const totalRateCost = totalGoal > 0 ? Math.round((totalActual / totalGoal) * 1000) / 10 : 0;

  return (
    <>
      {/* 이슈 + 투입원가 2분할 (가로 배치) */}
      <div className="grid grid-cols-2 gap-4">
        {/* 이슈 (Quality) */}
        <div className="bg-white rounded-xl border border-gray-200 p-5 flex flex-col shadow-sm">
          <h3 className="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2 shrink-0">
            <AlertCircle size={16} className="text-red-500" />
            이슈 (Quality)
          </h3>
          <div className="flex-1 grid grid-cols-2 gap-3 content-center">
            <MiniStat label="발생" value={issueTotal} color="text-gray-800" />
            <MiniStat label="조치" value={issueDone} color="text-green-600" />
            <MiniStat label="미결" value={issueMiss} color="text-red-500" />
            <MiniStat label="조치율" value={`${issueRate}%`} color="text-primary" />
          </div>
        </div>

        {/* 투입원가현황 — 원본 dashboard.jsp 5행 테이블 */}
        <div className="bg-white rounded-xl border border-gray-200 p-5 flex flex-col shadow-sm">
          <h3 className="text-sm font-semibold text-gray-700 mb-4 flex items-center gap-2 shrink-0">
            <BarChart3 size={16} className="text-primary" />
            투입원가현황
          </h3>
          <div className="flex-1 overflow-auto">
            <table className="w-full text-xs border-collapse">
              <thead>
                <tr className="bg-gray-600 text-white">
                  <th className="border border-gray-300 px-2 py-1.5 font-semibold">수주가(원)</th>
                  <th className="border border-gray-300 px-2 py-1.5 font-semibold">항목</th>
                  <th className="border border-gray-300 px-2 py-1.5 font-semibold">목표원가(원)</th>
                  <th className="border border-gray-300 px-2 py-1.5 font-semibold">투입원가(원)</th>
                  <th className="border border-gray-300 px-2 py-1.5 font-semibold">투입율(%)</th>
                </tr>
              </thead>
              <tbody className="text-gray-700">
                <tr>
                  <td rowSpan={5} className="border border-gray-300 px-2 py-2 text-right align-middle">{numberWithCommas(contractPrice)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-center">재료비</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{numberWithCommas(materialGoal)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{numberWithCommas(materialActual)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{materialRate}</td>
                </tr>
                <tr>
                  <td className="border border-gray-300 px-2 py-1.5 text-center">노무비</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{numberWithCommas(laborGoal)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{numberWithCommas(laborActual)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{laborRate}</td>
                </tr>
                <tr>
                  <td className="border border-gray-300 px-2 py-1.5 text-center">경비</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{numberWithCommas(expenseGoal)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{numberWithCommas(expenseActual)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{expenseRate}</td>
                </tr>
                <tr>
                  <td className="border border-gray-300 px-2 py-1.5 text-center">관리비</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{numberWithCommas(mgmtGoal)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{numberWithCommas(mgmtActual)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right">{mgmtRate}</td>
                </tr>
                <tr style={{ backgroundColor: "#efb3b3" }}>
                  <td className="border border-gray-300 px-2 py-1.5 text-center font-semibold">계</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right font-semibold">{numberWithCommas(totalGoal)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right font-semibold">{numberWithCommas(totalActual)}</td>
                  <td className="border border-gray-300 px-2 py-1.5 text-right font-semibold">{totalRateCost}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </>
  );
}

function MiniStat({ label, value, color }: { label: string; value: number | string; color: string }) {
  return (
    <div className="bg-gray-50 rounded-lg p-4 text-center">
      <div className="text-xs text-gray-500 mb-1">{label}</div>
      <div className={`text-2xl font-bold ${color}`}>{value}</div>
    </div>
  );
}

function CountBadge({ label, value, color, active, onClick }: {
  label: string; value: number; color: "blue" | "red";
  active?: boolean; onClick?: () => void;
}) {
  const numColor = value > 0 ? (color === "red" ? "text-red-500" : "text-blue-600") : "text-gray-300";
  const bg = active ? (color === "red" ? "bg-red-50" : "bg-blue-50") : "hover:bg-gray-50";
  return (
    <button type="button" onClick={onClick}
      className={`flex flex-col items-center justify-center rounded-lg py-2 transition-colors ${bg}`}>
      <div className={`text-3xl font-bold ${numColor}`}>{numberWithCommas(value)}</div>
      <div className="text-xs text-gray-500 mt-0.5">({label})</div>
    </button>
  );
}

