'use client';

/**
 * 설비 현황 대시보드
 *
 * 통계 카드 + 이번달 점검 현황 / 설비 유형별 현황 + 최근 수리이력
 */

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Loader2, ArrowRight } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  getEquipmentStats,
  getRepairList,
} from '@/components/quality/EquipmentManagement/actions';
import type { EquipmentStats, EquipmentRepair } from '@/components/quality/EquipmentManagement/types';
import {
  REPAIR_TYPE_LABEL,
  REPAIR_TYPE_COLOR,
} from '@/components/quality/EquipmentManagement/types';

export function EquipmentStatusDashboard() {
  const router = useRouter();
  const [stats, setStats] = useState<EquipmentStats | null>(null);
  const [recentRepairs, setRecentRepairs] = useState<EquipmentRepair[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      getEquipmentStats(),
      getRepairList({ perPage: 5 }),
    ]).then(([statsResult, repairsResult]) => {
      if (statsResult.success && statsResult.data) {
        setStats(statsResult.data);
      }
      if (repairsResult.success) {
        setRecentRepairs(repairsResult.data);
      }
      setIsLoading(false);
    });
  }, []);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = String(now.getMonth() + 1).padStart(2, '0');

  return (
    <div className="space-y-6 p-3 md:p-6">
      <div>
        <h1 className="text-xl font-bold">설비 현황</h1>
        <p className="text-sm text-muted-foreground">{currentYear}년 {currentMonth}월 {String(now.getDate()).padStart(2, '0')}일 기준</p>
      </div>

      {/* 통계 카드 4개 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {[
          { label: '총 설비', value: stats?.total ?? 0, color: '' },
          { label: '가동 중', value: stats?.active ?? 0, color: 'text-green-600' },
          { label: '유휴', value: stats?.idle ?? 0, color: 'text-yellow-600' },
          { label: '폐기', value: stats?.disposed ?? 0, color: 'text-red-600' },
        ].map((card) => (
          <Card key={card.label}>
            <CardContent className="pt-4 pb-4">
              <p className="text-sm text-muted-foreground">{card.label}</p>
              <p className={`text-3xl font-bold ${card.color}`}>{card.value}</p>
              <p className="text-xs text-muted-foreground">대</p>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 이번달 점검 현황 + 설비 유형별 현황 (2컬럼) */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {/* 이번달 점검 현황 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">이번달 점검 현황</CardTitle>
            <p className="text-sm text-muted-foreground">{currentYear}년 {currentMonth}월</p>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-sm">점검 대상</span>
                <span className="text-sm font-bold">{stats?.inspectionStats?.targetCount ?? 0}대</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm">점검 완료</span>
                <span className="text-sm font-bold text-green-600">{stats?.inspectionStats?.completedCount ?? 0}대</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm">이상 발견</span>
                <span className="text-sm font-bold">{stats?.inspectionStats?.issueCount ?? 0}건</span>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 설비 유형별 현황 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-base">설비 유형별 현황</CardTitle>
          </CardHeader>
          <CardContent>
            {(!stats?.typeDistribution || stats.typeDistribution.length === 0) ? (
              <div className="text-center py-6 text-muted-foreground text-sm">
                데이터가 없습니다.
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>유형</TableHead>
                    <TableHead className="w-[100px] text-right">설비 수</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {stats.typeDistribution.map((item) => (
                    <TableRow key={item.equipmentType}>
                      <TableCell>{item.equipmentType}</TableCell>
                      <TableCell className="text-right">{item.count}대</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 최근 수리이력 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="text-base">최근 수리이력</CardTitle>
            <Button
              variant="ghost"
              size="sm"
              className="text-blue-600"
              onClick={() => router.push('/quality/equipment-repairs')}
            >
              전체보기
              <ArrowRight className="h-4 w-4 ml-1" />
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {recentRepairs.length === 0 ? (
            <div className="text-center py-6 text-muted-foreground text-sm">
              최근 수리이력이 없습니다.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>수리일</TableHead>
                  <TableHead>설비</TableHead>
                  <TableHead>내용</TableHead>
                  <TableHead className="w-[80px] text-center">구분</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {recentRepairs.map((repair) => (
                  <TableRow key={repair.id}>
                    <TableCell>{repair.repairDate}</TableCell>
                    <TableCell>{repair.equipmentCode} {repair.equipmentName}</TableCell>
                    <TableCell className="truncate max-w-[200px]">{repair.description || '-'}</TableCell>
                    <TableCell className="text-center">
                      {repair.repairType ? (
                        <Badge className={REPAIR_TYPE_COLOR[repair.repairType]} variant="secondary">
                          {REPAIR_TYPE_LABEL[repair.repairType]}
                        </Badge>
                      ) : '-'}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
