'use client';

import { useState } from 'react';
import { Target, ChevronRight, ArrowLeft } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { DashboardSwitcher } from '@/components/business/DashboardSwitcher';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, ResponsiveContainer, Tooltip, Cell } from 'recharts';
import { formatNumber } from '@/lib/utils/amount';

// ============================================
// Mock 데이터
// ============================================

interface KpiItem {
  id: string;
  label: string;
  value: string;
  rawValue: number;
  change: string;
  up: boolean;
  color: string;
  bgColor: string;
}

interface DetailItem {
  id: string;
  name: string;
  amount: string;
  rawAmount: number;
  sub: string;
  status?: string;
  items?: SubDetailItem[];
}

interface SubDetailItem {
  label: string;
  value: string;
  date?: string;
}

const kpis: KpiItem[] = [
  { id: 'revenue', label: '당월 매출', value: '12.8억', rawValue: 1280000000, change: '+8.3%', up: true, color: '#3b82f6', bgColor: 'bg-blue-50 border-blue-200' },
  { id: 'expense', label: '당월 지출', value: '8.5억', rawValue: 850000000, change: '-3.2%', up: false, color: '#f97316', bgColor: 'bg-orange-50 border-orange-200' },
  { id: 'receivable', label: '미수금', value: '10.1억', rawValue: 1010000000, change: '+2.1%', up: true, color: '#ef4444', bgColor: 'bg-red-50 border-red-200' },
  { id: 'cash', label: '현금성 자산', value: '305억', rawValue: 30500000000, change: '+5.2%', up: true, color: '#10b981', bgColor: 'bg-green-50 border-green-200' },
];

const detailData: Record<string, DetailItem[]> = {
  revenue: [
    { id: 'r1', name: '(주)대한건설', amount: '4.5억', rawAmount: 450000000, sub: '전동개폐기 SET 외 2건', status: '진행중', items: [
      { label: '전동개폐기 SET', value: '2.5억', date: '2026-01-15' },
      { label: '자동제어 시스템', value: '1.5억', date: '2026-02-01' },
      { label: '부자재', value: '5,000만', date: '2026-02-05' },
    ]},
    { id: 'r2', name: '삼성엔지니어링', amount: '3.2억', rawAmount: 320000000, sub: '자동제어 시스템', status: '완료', items: [
      { label: '자동제어 시스템 본체', value: '2.8억', date: '2026-01-20' },
      { label: '설치 용역', value: '4,000만', date: '2026-01-28' },
    ]},
    { id: 'r3', name: '현대건설', amount: '2.8억', rawAmount: 280000000, sub: '환기 시스템', status: '진행중', items: [
      { label: '환기 시스템 일식', value: '2.8억', date: '2026-02-03' },
    ]},
    { id: 'r4', name: 'LG전자', amount: '1.5억', rawAmount: 150000000, sub: '공조기 제어반', status: '대기', items: [
      { label: '공조기 제어반', value: '1.5억', date: '2026-02-10' },
    ]},
    { id: 'r5', name: 'SK에코플랜트', amount: '0.8억', rawAmount: 80000000, sub: '모터 제어반', status: '진행중', items: [
      { label: '모터 제어반', value: '8,000만', date: '2026-02-08' },
    ]},
  ],
  expense: [
    { id: 'e1', name: '매입', amount: '5,234만', rawAmount: 52340000, sub: '원자재 구매', items: [
      { label: '동 파이프', value: '2,100만', date: '2026-02-01' },
      { label: '전자부품', value: '1,800만', date: '2026-02-03' },
      { label: '기타 자재', value: '1,334만', date: '2026-02-05' },
    ]},
    { id: 'e2', name: '인건비', amount: '3,200만', rawAmount: 32000000, sub: '정규직 28명', items: [
      { label: '급여', value: '2,600만' },
      { label: '4대보험', value: '400만' },
      { label: '수당', value: '200만' },
    ]},
    { id: 'e3', name: '운영비', amount: '1,580만', rawAmount: 15800000, sub: '임대료, 유틸리티 등', items: [
      { label: '임대료', value: '800만' },
      { label: '유틸리티', value: '380만' },
      { label: '통신/IT', value: '250만' },
      { label: '기타', value: '150만' },
    ]},
    { id: 'e4', name: '카드', amount: '985만', rawAmount: 9850000, sub: '법인카드 3매', items: [
      { label: '신한카드', value: '450만' },
      { label: '국민카드', value: '320만' },
      { label: '하나카드', value: '215만' },
    ]},
  ],
  receivable: [
    { id: 'v1', name: '(주)대한건설', amount: '4,000만', rawAmount: 40000000, sub: '45일 경과', status: '정상', items: [
      { label: '매출액', value: '1.2억' },
      { label: '입금액', value: '8,000만' },
      { label: '미수금', value: '4,000만' },
      { label: '최근 입금일', value: '2026-01-25' },
    ]},
    { id: 'v2', name: '삼성엔지니어링', amount: '1억', rawAmount: 100000000, sub: '92일 경과', status: '주의', items: [
      { label: '매출액', value: '2.5억' },
      { label: '입금액', value: '1.5억' },
      { label: '미수금', value: '1억' },
      { label: '최근 입금일', value: '2025-11-15' },
    ]},
    { id: 'v3', name: 'SK에코플랜트', amount: '4,400만', rawAmount: 44000000, sub: '30일 경과', status: '정상', items: [
      { label: '매출액', value: '8,900만' },
      { label: '입금액', value: '4,500만' },
      { label: '미수금', value: '4,400만' },
      { label: '최근 입금일', value: '2026-01-10' },
    ]},
    { id: 'v4', name: 'LG전자', amount: '3,200만', rawAmount: 32000000, sub: '120일 경과', status: '위험', items: [
      { label: '매출액', value: '3,200만' },
      { label: '입금액', value: '0원' },
      { label: '미수금', value: '3,200만' },
      { label: '최근 입금일', value: '없음' },
    ]},
  ],
  cash: [
    { id: 'c1', name: '보통예금', amount: '180억', rawAmount: 18000000000, sub: '신한은행 외 3곳', items: [
      { label: '신한은행', value: '82억' },
      { label: '국민은행', value: '55억' },
      { label: '하나은행', value: '30억' },
      { label: '기업은행', value: '13억' },
    ]},
    { id: 'c2', name: '정기예금', amount: '100억', rawAmount: 10000000000, sub: '만기 2026-06', items: [
      { label: '신한은행 정기예금', value: '50억', date: '만기: 2026-06-15' },
      { label: '국민은행 정기예금', value: '30억', date: '만기: 2026-08-20' },
      { label: '하나은행 정기예금', value: '20억', date: '만기: 2026-12-01' },
    ]},
    { id: 'c3', name: '단기금융상품', amount: '25억', rawAmount: 2500000000, sub: 'MMF, CMA 등', items: [
      { label: 'MMF', value: '15억' },
      { label: 'CMA', value: '10억' },
    ]},
  ],
};

// ============================================
// 레벨별 컴포넌트
// ============================================

function Level1({ kpiList, onSelect }: { kpiList: KpiItem[]; onSelect: (id: string) => void }) {
  const chartData = kpiList.map((k) => ({ name: k.label, value: k.rawValue / 100000000, color: k.color }));

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {kpiList.map((kpi) => (
          <button
            key={kpi.id}
            onClick={() => onSelect(kpi.id)}
            className={`${kpi.bgColor} rounded-xl p-5 text-left border hover:ring-2 hover:ring-primary/30 transition-all group`}
          >
            <p className="text-xs text-muted-foreground">{kpi.label}</p>
            <p className="text-2xl lg:text-3xl font-bold mt-2" style={{ color: kpi.color }}>{kpi.value}</p>
            <div className="flex items-center justify-between mt-2">
              <p className={`text-xs ${kpi.up ? 'text-green-500' : 'text-red-500'}`}>{kpi.change}</p>
              <ChevronRight className="w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
            </div>
          </button>
        ))}
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base font-semibold">주요 지표 비교 (억원)</CardTitle>
        </CardHeader>
        <CardContent>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart data={chartData} layout="vertical">
              <CartesianGrid strokeDasharray="3 3" horizontal={false} />
              <XAxis type="number" tick={{ fontSize: 11 }} tickFormatter={(v: number) => `${v}억`} />
              <YAxis dataKey="name" type="category" tick={{ fontSize: 12 }} width={80} />
              <Tooltip formatter={(v) => `${Number(v ?? 0).toFixed(1)}억원`} contentStyle={{ fontSize: '12px', borderRadius: '8px' }} />
              <Bar dataKey="value" radius={[0, 4, 4, 0]} maxBarSize={28}>
                {chartData.map((entry, index) => (
                  <Cell key={index} fill={entry.color} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </CardContent>
      </Card>

      <p className="text-center text-sm text-muted-foreground">카드를 클릭하면 상세 내역을 확인할 수 있습니다</p>
    </div>
  );
}

function Level2({ kpi, items, onSelect, onBack }: { kpi: KpiItem; items: DetailItem[]; onSelect: (item: DetailItem) => void; onBack: () => void }) {
  const chartData = items.map((item) => ({ name: item.name, value: item.rawAmount }));

  return (
    <div className="space-y-6">
      <button onClick={onBack} className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors">
        <ArrowLeft className="w-4 h-4" />
        전체 요약으로 돌아가기
      </button>

      <div className={`${kpi.bgColor} rounded-xl p-5 border`}>
        <p className="text-sm text-muted-foreground">{kpi.label}</p>
        <p className="text-3xl font-bold mt-1" style={{ color: kpi.color }}>{kpi.value}</p>
        <p className={`text-sm mt-1 ${kpi.up ? 'text-green-500' : 'text-red-500'}`}>{kpi.change} 전월 대비</p>
      </div>

      {chartData.length > 0 && chartData[0].value > 0 && (
        <Card>
          <CardContent className="pt-4">
            <ResponsiveContainer width="100%" height={items.length * 44 + 20}>
              <BarChart data={chartData} layout="vertical">
                <CartesianGrid strokeDasharray="3 3" horizontal={false} />
                <XAxis type="number" tick={{ fontSize: 11 }} />
                <YAxis dataKey="name" type="category" tick={{ fontSize: 11 }} width={100} />
                <Tooltip formatter={(v) => `${formatNumber(Number(v ?? 0))}원`} contentStyle={{ fontSize: '12px', borderRadius: '8px' }} />
                <Bar dataKey="value" fill={kpi.color} radius={[0, 4, 4, 0]} maxBarSize={22} />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      )}

      <div className="space-y-2">
        {items.map((item) => (
          <button
            key={item.id}
            onClick={() => onSelect(item)}
            className="w-full flex items-center justify-between p-4 rounded-xl border hover:bg-muted/30 hover:ring-1 hover:ring-primary/20 transition-all text-left group"
          >
            <div>
              <p className="font-semibold">{item.name}</p>
              <p className="text-xs text-muted-foreground mt-0.5">{item.sub}</p>
            </div>
            <div className="flex items-center gap-3">
              <div className="text-right">
                <p className="font-bold" style={{ color: kpi.color }}>{item.amount}</p>
                {item.status && <StatusBadge status={item.status} />}
              </div>
              <ChevronRight className="w-4 h-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" />
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function Level3({ kpi, item, onBack }: { kpi: KpiItem; item: DetailItem; onBack: () => void }) {
  return (
    <div className="space-y-6">
      <button onClick={onBack} className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors">
        <ArrowLeft className="w-4 h-4" />
        {kpi.label} 목록으로 돌아가기
      </button>

      <Card>
        <CardHeader className="border-b">
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="text-lg">{item.name}</CardTitle>
              <p className="text-sm text-muted-foreground mt-1">{item.sub}</p>
            </div>
            <div className="text-right">
              <p className="text-2xl font-bold" style={{ color: kpi.color }}>{item.amount}</p>
              {item.status && <StatusBadge status={item.status} />}
            </div>
          </div>
        </CardHeader>
        <CardContent className="pt-4">
          {item.items && item.items.length > 0 ? (
            <div className="space-y-3">
              {item.items.map((sub, idx) => (
                <div key={idx} className="flex items-center justify-between py-3 border-b last:border-0">
                  <div>
                    <p className="text-sm font-medium">{sub.label}</p>
                    {sub.date && <p className="text-xs text-muted-foreground mt-0.5">{sub.date}</p>}
                  </div>
                  <p className="font-semibold text-sm">{sub.value}</p>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-sm text-muted-foreground text-center py-8">상세 데이터가 없습니다.</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const styles: Record<string, string> = {
    '정상': 'bg-green-100 text-green-700', '주의': 'bg-yellow-100 text-yellow-700', '위험': 'bg-red-100 text-red-700',
    '진행중': 'bg-blue-100 text-blue-700', '완료': 'bg-green-100 text-green-700', '대기': 'bg-gray-100 text-gray-600',
  };
  return <span className={`inline-block px-2 py-0.5 rounded-full text-[10px] font-medium ${styles[status] ?? 'bg-gray-100 text-gray-600'}`}>{status}</span>;
}

// ============================================
// Breadcrumb
// ============================================

function Breadcrumb({ items }: { items: { label: string; onClick?: () => void }[] }) {
  return (
    <nav className="flex items-center gap-1.5 text-sm text-muted-foreground mb-4">
      {items.map((item, idx) => {
        const isCurrent = idx === items.length - 1;
        return (
          <span key={idx} className="flex items-center gap-1.5">
            {idx > 0 && <ChevronRight className="w-3.5 h-3.5" />}
            {item.onClick ? (
              <button onClick={item.onClick} className="hover:text-foreground transition-colors">{item.label}</button>
            ) : (
              <span className="inline-flex items-center gap-1 bg-primary/10 text-primary font-medium px-2 py-0.5 rounded-md">
                {isCurrent && <ChevronRight className="w-3 h-3" />}
                {item.label}
              </span>
            )}
          </span>
        );
      })}
    </nav>
  );
}

// ============================================
// 메인 컴포넌트
// ============================================

export function DashboardType4() {
  const [level, setLevel] = useState<1 | 2 | 3>(1);
  const [selectedKpi, setSelectedKpi] = useState<string | null>(null);
  const [selectedItem, setSelectedItem] = useState<DetailItem | null>(null);

  const handleKpiSelect = (id: string) => {
    setSelectedKpi(id);
    setLevel(2);
  };

  const handleItemSelect = (item: DetailItem) => {
    setSelectedItem(item);
    setLevel(3);
  };

  const goToLevel1 = () => {
    setLevel(1);
    setSelectedKpi(null);
    setSelectedItem(null);
  };

  const goToLevel2 = () => {
    setLevel(2);
    setSelectedItem(null);
  };

  const currentKpi = kpis.find((k) => k.id === selectedKpi);
  const currentItems = selectedKpi ? detailData[selectedKpi] ?? [] : [];

  const breadcrumbItems = [
    { label: '전체 요약', onClick: level > 1 ? goToLevel1 : undefined },
    ...(level >= 2 && currentKpi ? [{ label: currentKpi.label, onClick: level > 2 ? goToLevel2 : undefined }] : []),
    ...(level === 3 && selectedItem ? [{ label: selectedItem.name }] : []),
  ];

  return (
    <PageLayout>
      <div className="p-3 md:p-6">
        <PageHeader
          title="KPI 드릴다운"
          description="숫자를 클릭하면 점점 상세해집니다."
          icon={Target}
          actions={<DashboardSwitcher />}
        />

        <div className="mt-6">
          <Breadcrumb items={breadcrumbItems} />

          {level === 1 && (
            <Level1 kpiList={kpis} onSelect={handleKpiSelect} />
          )}
          {level === 2 && currentKpi && (
            <Level2 kpi={currentKpi} items={currentItems} onSelect={handleItemSelect} onBack={goToLevel1} />
          )}
          {level === 3 && currentKpi && selectedItem && (
            <Level3 kpi={currentKpi} item={selectedItem} onBack={goToLevel2} />
          )}
        </div>
      </div>
    </PageLayout>
  );
}
