'use client';

import { useState } from 'react';
import {
  TrendingUp,
  TrendingDown,
  ArrowUpRight,
  ArrowDownRight,
  BarChart3,
  Target,
  Calendar,
  DollarSign,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { MultiSelectCombobox } from '@/components/ui/multi-select-combobox';
import { formatCompactAmount } from '@/lib/utils/amount';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from 'recharts';
import { formatKoreanAmount } from '@/lib/utils/amount';
import { CollapsibleDashboardCard } from '../components';
import type { SalesStatusData } from '../types';

interface SalesStatusSectionProps {
  data: SalesStatusData;
}


export function SalesStatusSection({ data }: SalesStatusSectionProps) {
  const [clientFilter, setClientFilter] = useState<string[]>([]);

  const filteredItems = data.dailyItems
    .filter((item) => clientFilter.length === 0 || clientFilter.includes(item.client));

  const clients = [...new Set(data.dailyItems.map((item) => item.client))];

  return (
    <div className="space-y-6">
    <CollapsibleDashboardCard
      icon={<BarChart3 className="h-5 w-5 text-white" />}
      title="매출 현황"
      subtitle="당월 매출 실적"
      rightElement={
        <Badge className="bg-blue-500 text-white border-none hover:opacity-90">
          당월
        </Badge>
      }
    >
        {/* 통계카드 4개 */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
          {/* 누적 매출 */}
          <div className="rounded-xl p-4 border bg-blue-50 border-blue-200 dark:bg-blue-900/30 dark:border-blue-800">
            <div className="flex items-center gap-2 mb-2">
              <div style={{ backgroundColor: '#3b82f6' }} className="p-1.5 rounded-lg">
                <DollarSign className="h-4 w-4 text-white" />
              </div>
              <span className="text-sm font-medium text-blue-700 dark:text-blue-300">누적 매출</span>
            </div>
            <span className="text-xl font-bold text-foreground">
              {formatKoreanAmount(data.cumulativeSales)}
            </span>
          </div>

          {/* 달성률 */}
          <div className="rounded-xl p-4 border bg-green-50 border-green-200 dark:bg-green-900/30 dark:border-green-800">
            <div className="flex items-center gap-2 mb-2">
              <div style={{ backgroundColor: '#22c55e' }} className="p-1.5 rounded-lg">
                <Target className="h-4 w-4 text-white" />
              </div>
              <span className="text-sm font-medium text-green-700 dark:text-green-300">달성률</span>
            </div>
            <span className="text-xl font-bold text-foreground">
              {data.achievementRate}%
            </span>
          </div>

          {/* 전년 동기 대비 */}
          <div
            className={`rounded-xl p-4 border ${data.yoyChange >= 0 ? 'bg-red-50 border-red-200 dark:bg-red-900/30 dark:border-red-800' : 'bg-blue-50 border-blue-200 dark:bg-blue-900/30 dark:border-blue-800'}`}
          >
            <div className="flex items-center gap-2 mb-2">
              <div style={{ backgroundColor: data.yoyChange >= 0 ? '#ef4444' : '#3b82f6' }} className="p-1.5 rounded-lg">
                {data.yoyChange >= 0
                  ? <TrendingUp className="h-4 w-4 text-white" />
                  : <TrendingDown className="h-4 w-4 text-white" />}
              </div>
              <span className={`text-sm font-medium ${data.yoyChange >= 0 ? 'text-red-700 dark:text-red-300' : 'text-blue-700 dark:text-blue-300'}`}>전년 동기 대비</span>
            </div>
            <div className="flex items-center gap-1">
              <span className="text-xl font-bold text-foreground">
                {data.yoyChange >= 0 ? '+' : ''}{data.yoyChange}%
              </span>
              {data.yoyChange >= 0
                ? <ArrowUpRight className="h-4 w-4 text-red-500" />
                : <ArrowDownRight className="h-4 w-4 text-blue-500" />}
            </div>
          </div>

          {/* 당월 매출 */}
          <div className="rounded-xl p-4 border bg-purple-50 border-purple-200 dark:bg-purple-900/30 dark:border-purple-800">
            <div className="flex items-center gap-2 mb-2">
              <div style={{ backgroundColor: '#a855f7' }} className="p-1.5 rounded-lg">
                <Calendar className="h-4 w-4 text-white" />
              </div>
              <span className="text-sm font-medium text-purple-700 dark:text-purple-300">당월 매출</span>
            </div>
            <span className="text-xl font-bold text-foreground">
              {formatKoreanAmount(data.monthlySales)}
            </span>
          </div>
        </div>

        {/* 차트 2열 */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
          {/* 월별 매출 추이 */}
          <div className="border border-border rounded-lg p-4">
            <h4 className="text-sm font-semibold text-foreground mb-3">월별 매출 추이</h4>
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={data.monthlyTrend}>
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                <XAxis dataKey="month" tick={{ fontSize: 12 }} />
                <YAxis tickFormatter={formatCompactAmount} tick={{ fontSize: 11 }} />
                <Tooltip
                  formatter={(value) => [formatKoreanAmount(Number(value) || 0), '매출']}
                />
                <Bar dataKey="amount" fill="#3b82f6" radius={[4, 4, 0, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>

          {/* 거래처별 매출 (수평 Bar) */}
          <div className="border border-border rounded-lg p-4">
            <h4 className="text-sm font-semibold text-foreground mb-3">거래처별 매출</h4>
            <ResponsiveContainer width="100%" height={200}>
              <BarChart data={data.clientSales} layout="vertical">
                <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                <XAxis type="number" tickFormatter={formatCompactAmount} tick={{ fontSize: 11 }} />
                <YAxis type="category" dataKey="name" tick={{ fontSize: 12 }} width={80} />
                <Tooltip
                  formatter={(value) => [formatKoreanAmount(Number(value) || 0), '매출']}
                />
                <Bar dataKey="amount" fill="#10b981" radius={[0, 4, 4, 0]} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>

    </CollapsibleDashboardCard>

    {/* 당월 매출 내역 (별도 카드) */}
    <CollapsibleDashboardCard
      icon={<BarChart3 className="h-5 w-5 text-white" />}
      title="당월 매출 내역"
      subtitle="당월 매출 거래 상세"
      bodyClassName="p-0"
    >
        <div className="p-3 bg-muted/50 border-b border-border space-y-2">
          <div className="text-sm text-muted-foreground">총 {filteredItems.length}건</div>
          <MultiSelectCombobox
            options={clients.map((c) => ({ value: c, label: c }))}
            value={clientFilter}
            onChange={setClientFilter}
            placeholder="전체 거래처"
            className="w-full h-8 text-xs"
          />
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[500px]">
            <thead>
              <tr className="bg-muted/50 border-b border-border">
                <th className="px-4 py-2 text-left text-muted-foreground font-medium">날짜</th>
                <th className="px-4 py-2 text-left text-muted-foreground font-medium">거래처</th>
                <th className="px-4 py-2 text-left text-muted-foreground font-medium">품목</th>
                <th className="px-4 py-2 text-right text-muted-foreground font-medium">금액</th>
                <th className="px-4 py-2 text-center text-muted-foreground font-medium">상태</th>
              </tr>
            </thead>
            <tbody>
              {filteredItems.map((item, idx) => (
                <tr key={idx} className="border-b border-border last:border-b-0 hover:bg-muted/30">
                  <td className="px-4 py-2 text-muted-foreground">{item.date}</td>
                  <td className="px-4 py-2 text-muted-foreground">{item.client}</td>
                  <td className="px-4 py-2 text-muted-foreground">{item.item}</td>
                  <td className="px-4 py-2 text-right text-foreground font-medium">
                    {item.amount.toLocaleString()}원
                  </td>
                  <td className="px-4 py-2 text-center">
                    <Badge
                      variant="outline"
                      className={
                        item.status === '입금완료'
                          ? 'text-green-600 border-green-200 bg-green-50 dark:text-green-400 dark:border-green-800 dark:bg-green-900/30'
                          : item.status === '미입금'
                          ? 'text-red-600 border-red-200 bg-red-50 dark:text-red-400 dark:border-red-800 dark:bg-red-900/30'
                          : 'text-orange-600 border-orange-200 bg-orange-50 dark:text-orange-400 dark:border-orange-800 dark:bg-orange-900/30'
                      }
                    >
                      {item.status}
                    </Badge>
                  </td>
                </tr>
              ))}
            </tbody>
            <tfoot>
              <tr className="bg-muted font-semibold">
                <td className="px-4 py-2 text-muted-foreground" colSpan={3}>합계</td>
                <td className="px-4 py-2 text-right text-foreground">
                  {filteredItems.reduce((sum, item) => sum + item.amount, 0).toLocaleString()}원
                </td>
                <td />
              </tr>
            </tfoot>
          </table>
        </div>
    </CollapsibleDashboardCard>
    </div>
  );
}
