'use client';

/**
 * 설비 엑셀 Import 페이지
 *
 * 엑셀 파일 업로드 → 미리보기 → 일괄 등록
 */

import { useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Upload, FileSpreadsheet, Loader2, Download } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

interface ImportRow {
  equipmentCode: string;
  name: string;
  equipmentType: string;
  specification: string;
  manufacturer: string;
  location: string;
  productionLine: string;
  status: string;
  [key: string]: string;
}

export function EquipmentImport() {
  const router = useRouter();
  const [file, setFile] = useState<File | null>(null);
  const [previewData, setPreviewData] = useState<ImportRow[]>([]);
  const [isUploading, setIsUploading] = useState(false);
  const [isImporting, setIsImporting] = useState(false);

  const handleFileChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const selected = e.target.files?.[0];
    if (!selected) return;

    if (!selected.name.match(/\.(xlsx|xls|csv)$/i)) {
      toast.error('엑셀 파일(.xlsx, .xls) 또는 CSV 파일만 업로드 가능합니다.');
      return;
    }
    setFile(selected);
    setPreviewData([]);
  }, []);

  const handleUploadPreview = useCallback(async () => {
    if (!file) {
      toast.error('파일을 선택하세요.');
      return;
    }
    setIsUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch('/api/proxy/equipment/import/preview', {
        method: 'POST',
        body: formData,
      });
      const result = await response.json();

      if (result.success && result.data) {
        setPreviewData(result.data);
        toast.success(`${result.data.length}건의 데이터가 확인되었습니다.`);
      } else {
        toast.error(result.message || '파일 읽기에 실패했습니다.');
      }
    } catch {
      toast.error('파일 업로드 중 오류가 발생했습니다.');
    } finally {
      setIsUploading(false);
    }
  }, [file]);

  const handleImport = useCallback(async () => {
    if (previewData.length === 0) return;
    setIsImporting(true);
    try {
      const formData = new FormData();
      formData.append('file', file!);

      const response = await fetch('/api/proxy/equipment/import', {
        method: 'POST',
        body: formData,
      });
      const result = await response.json();

      if (result.success) {
        toast.success(`${result.data?.imported || previewData.length}건이 등록되었습니다.`);
        router.push('/quality/equipment');
      } else {
        toast.error(result.message || 'Import에 실패했습니다.');
      }
    } catch {
      toast.error('Import 중 오류가 발생했습니다.');
    } finally {
      setIsImporting(false);
    }
  }, [file, previewData, router]);

  return (
    <div className="space-y-6 p-3 md:p-6">
      {/* 헤더 */}
      <div>
        <h1 className="text-xl font-bold">설비 엑셀 Import</h1>
        <Button
          variant="link"
          className="text-muted-foreground p-0 h-auto"
          onClick={() => router.push('/quality/equipment')}
        >
          ← 목록으로
        </Button>
      </div>

      {/* 파일 업로드 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">파일 업로드</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <Input
            type="file"
            accept=".xlsx,.xls,.csv"
            onChange={handleFileChange}
          />
          <Button onClick={handleUploadPreview} disabled={!file || isUploading} className="w-full">
            {isUploading ? (
              <Loader2 className="h-4 w-4 mr-1 animate-spin" />
            ) : (
              <Upload className="h-4 w-4 mr-1" />
            )}
            미리보기
          </Button>
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <FileSpreadsheet className="h-4 w-4 shrink-0" />
            <span>지원 형식: .xlsx, .xls, .csv</span>
          </div>
          <Button variant="link" size="sm" className="text-blue-600 p-0 h-auto">
            <Download className="h-3.5 w-3.5 mr-1" />
            양식 다운로드
          </Button>
        </CardContent>
      </Card>

      {/* 미리보기 */}
      {previewData.length > 0 && (
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <CardTitle className="text-base">
                미리보기 ({previewData.length}건)
              </CardTitle>
              <Button onClick={handleImport} disabled={isImporting}>
                {isImporting ? (
                  <Loader2 className="h-4 w-4 mr-1 animate-spin" />
                ) : (
                  <Upload className="h-4 w-4 mr-1" />
                )}
                일괄 등록
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[50px] text-center">No.</TableHead>
                    <TableHead>설비번호</TableHead>
                    <TableHead>설비명</TableHead>
                    <TableHead>유형</TableHead>
                    <TableHead>규격</TableHead>
                    <TableHead>제조사</TableHead>
                    <TableHead>위치</TableHead>
                    <TableHead>생산라인</TableHead>
                    <TableHead>상태</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {previewData.map((row, idx) => (
                    <TableRow key={idx}>
                      <TableCell className="text-center">{idx + 1}</TableCell>
                      <TableCell>{row.equipmentCode || '-'}</TableCell>
                      <TableCell>{row.name || '-'}</TableCell>
                      <TableCell>{row.equipmentType || '-'}</TableCell>
                      <TableCell>{row.specification || '-'}</TableCell>
                      <TableCell>{row.manufacturer || '-'}</TableCell>
                      <TableCell>{row.location || '-'}</TableCell>
                      <TableCell>{row.productionLine || '-'}</TableCell>
                      <TableCell>{row.status || '-'}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
