'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { StatCards } from '../StatCards';
import { ReceivableBarChart } from '../charts/ReceivableBarChart';
import type { SalesTabData } from '../hooks/useDashboardType2';

function LoadingSkeleton() {
  return (
    <div className="space-y-6">
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {[...Array(4)].map((_, i) => (
          <div key={i} className="animate-pulse bg-muted rounded-xl h-[88px]" />
        ))}
      </div>
      <div className="animate-pulse bg-muted rounded-xl h-[300px]" />
      <div className="animate-pulse bg-muted rounded-xl h-[250px]" />
    </div>
  );
}

function getReceivableRowClass(row: Record<string, string | number>): string {
  const days = String(row['경과일']);
  const num = parseInt(days);
  if (!isNaN(num)) {
    if (num >= 90) return 'bg-red-50';
    if (num >= 30) return 'bg-yellow-50';
  }
  return '';
}

function getDebtRowClass(row: Record<string, string | number>): string {
  const possibility = String(row['회수가능성']);
  if (possibility === '하') return 'bg-red-50';
  if (possibility === '상') return 'bg-green-50';
  return '';
}

export function SalesTab({ data }: { data: SalesTabData }) {
  if (data.loading) return <LoadingSkeleton />;

  return (
    <div className="space-y-6">
      <StatCards stats={data.stats} />

      <ReceivableBarChart data={data.receivableChartData} />

      <Card>
        <CardHeader>
          <CardTitle className="text-base font-semibold">미수금 현황</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full text-sm min-w-[700px]">
              <thead>
                <tr className="border-b bg-muted/50">
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">No</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">거래처</th>
                  <th className="px-4 py-3 text-right font-medium text-muted-foreground">매출액</th>
                  <th className="px-4 py-3 text-right font-medium text-muted-foreground">입금액</th>
                  <th className="px-4 py-3 text-right font-medium text-muted-foreground">미수금</th>
                  <th className="px-4 py-3 text-center font-medium text-muted-foreground">경과일</th>
                  <th className="px-4 py-3 text-center font-medium text-muted-foreground">상태</th>
                </tr>
              </thead>
              <tbody>
                {data.receivableData.map((row, i) => (
                  <tr key={i} className={`border-b last:border-0 hover:bg-muted/30 ${getReceivableRowClass(row)}`}>
                    <td className="px-4 py-3 text-muted-foreground">{row.no}</td>
                    <td className="px-4 py-3 font-medium">{row['거래처']}</td>
                    <td className="px-4 py-3 text-right">{row['매출액']}</td>
                    <td className="px-4 py-3 text-right">{row['입금액']}</td>
                    <td className="px-4 py-3 text-right font-medium">{row['미수금']}</td>
                    <td className="px-4 py-3 text-center">{row['경과일']}</td>
                    <td className="px-4 py-3 text-center">
                      <StatusBadge status={row['상태'] as string} />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base font-semibold">채권추심 현황</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full text-sm min-w-[700px]">
              <thead>
                <tr className="border-b bg-muted/50">
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">No</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">거래처</th>
                  <th className="px-4 py-3 text-right font-medium text-muted-foreground">채권액</th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">추심단계</th>
                  <th className="px-4 py-3 text-center font-medium text-muted-foreground">경과일</th>
                  <th className="px-4 py-3 text-center font-medium text-muted-foreground">회수가능성</th>
                </tr>
              </thead>
              <tbody>
                {data.debtData.map((row, i) => (
                  <tr key={i} className={`border-b last:border-0 hover:bg-muted/30 ${getDebtRowClass(row)}`}>
                    <td className="px-4 py-3 text-muted-foreground">{row.no}</td>
                    <td className="px-4 py-3 font-medium">{row['거래처']}</td>
                    <td className="px-4 py-3 text-right">{row['채권액']}</td>
                    <td className="px-4 py-3">{row['추심단계']}</td>
                    <td className="px-4 py-3 text-center">{row['경과일']}</td>
                    <td className="px-4 py-3 text-center">
                      <PossibilityBadge level={row['회수가능성'] as string} />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

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

function PossibilityBadge({ level }: { level: string }) {
  const styles: Record<string, string> = {
    '상': 'bg-green-100 text-green-700',
    '중': 'bg-yellow-100 text-yellow-700',
    '하': 'bg-red-100 text-red-700',
  };
  return (
    <span className={`inline-block px-2.5 py-0.5 rounded-full text-xs font-medium ${styles[level] ?? 'bg-gray-100 text-gray-600'}`}>
      {level}
    </span>
  );
}
