'use client';

import { useState, useRef } from 'react';

interface CsvViewerProps {
  onFileSelect?: (file: File) => void;
  onDataParsed?: (data: string[][]) => void;
}

export default function CsvViewer({ onFileSelect, onDataParsed }: CsvViewerProps) {
  const [csvData, setCsvData] = useState<string[][]>([]);
  const [headers, setHeaders] = useState<string[]>([]);
  const [rows, setRows] = useState<string[][]>([]);
  const [fileName, setFileName] = useState<string>('');
  const fileInputRef = useRef<HTMLInputElement>(null);

  // CSV 파싱 함수
  const parseCsv = (text: string): string[][] => {
    const lines: string[][] = [];
    let currentLine: string[] = [];
    let currentField = '';
    let inQuotes = false;

    for (let i = 0; i < text.length; i++) {
      const char = text[i];
      const nextChar = text[i + 1];

      if (char === '"') {
        if (inQuotes && nextChar === '"') {
          // 이스케이프된 따옴표
          currentField += '"';
          i++; // 다음 문자 건너뛰기
        } else {
          // 따옴표 시작/끝
          inQuotes = !inQuotes;
        }
      } else if (char === ',' && !inQuotes) {
        // 필드 구분자
        currentLine.push(currentField.trim());
        currentField = '';
      } else if ((char === '\n' || char === '\r') && !inQuotes) {
        // 줄바꿈
        if (char === '\r' && nextChar === '\n') {
          i++; // \r\n 건너뛰기
        }
        if (currentField || currentLine.length > 0) {
          currentLine.push(currentField.trim());
          lines.push(currentLine);
          currentLine = [];
          currentField = '';
        }
      } else {
        currentField += char;
      }
    }

    // 마지막 필드 추가
    if (currentField || currentLine.length > 0) {
      currentLine.push(currentField.trim());
      lines.push(currentLine);
    }

    return lines;
  };

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

    // CSV 파일인지 확인
    if (!file.name.toLowerCase().endsWith('.csv')) {
      alert('CSV 파일만 업로드할 수 있습니다.');
      e.target.value = '';
      return;
    }

    setFileName(file.name);

    const reader = new FileReader();
    reader.onload = (event) => {
      const text = event.target?.result as string;
      if (!text) return;

      try {
        const parsed = parseCsv(text);
        
        if (parsed.length === 0) {
          alert('CSV 파일이 비어있습니다.');
          return;
        }

        // 첫 번째 줄을 헤더로 사용
        const csvHeaders = parsed[0];
        const csvRows = parsed.slice(1);

        setHeaders(csvHeaders);
        setRows(csvRows);
        setCsvData(parsed);

        // 콜백 호출
        if (onFileSelect) {
          onFileSelect(file);
        }
        if (onDataParsed) {
          onDataParsed(parsed);
        }
      } catch (error) {
        console.error('CSV 파싱 오류:', error);
        alert('CSV 파일을 읽는 중 오류가 발생했습니다.');
      }
    };

    reader.onerror = () => {
      alert('파일을 읽는 중 오류가 발생했습니다.');
    };

    reader.readAsText(file, 'UTF-8');
  };

  const handleClear = () => {
    setCsvData([]);
    setHeaders([]);
    setRows([]);
    setFileName('');
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  return (
    <div className="flex flex-col gap-4">
      {/* 파일 업로드 영역 */}
      <div className="flex items-center gap-4">
        <label className="h-[40px] px-4 py-2 border border-[#8c95a1] rounded-[8px] bg-white text-[16px] font-semibold leading-[1.5] text-[#4c5561] whitespace-nowrap hover:bg-gray-50 transition-colors cursor-pointer flex items-center justify-center">
          <span>CSV 파일 선택</span>
          <input
            ref={fileInputRef}
            type="file"
            accept=".csv,text/csv,application/vnd.ms-excel"
            className="hidden"
            onChange={handleFileChange}
          />
        </label>
        
        {fileName && (
          <div className="flex items-center gap-2">
            <span className="text-[15px] font-medium leading-[1.5] text-[#1b2027]">
              {fileName}
            </span>
            <button
              type="button"
              onClick={handleClear}
              className="text-[14px] font-normal leading-[1.5] text-[#8c95a1] hover:text-[#4c5561] transition-colors cursor-pointer"
            >
              삭제
            </button>
          </div>
        )}
      </div>

      {/* 표 영역 */}
      {csvData.length > 0 && (
        <div className="w-full border border-[#dee1e6] border-solid relative size-full bg-white">
          <div className="content-stretch flex flex-col items-start justify-center relative size-full">
            {/* 헤더 */}
            <div className="bg-[#f1f8ff] content-stretch flex h-[48px] items-center overflow-clip relative shrink-0 w-full">
              {headers.map((header, index) => {
                const isLast = index === headers.length - 1;
                return (
                  <div
                    key={index}
                    className={`border-[#dee1e6] border-[0px_1px_0px_0px] border-solid box-border content-stretch flex gap-[10px] h-full items-center justify-center px-[8px] py-[12px] relative shrink-0 ${
                      index === 0 ? 'w-[48px]' : index === 1 ? 'basis-0 grow min-h-px min-w-px' : 'w-[140px]'
                    }`}
                  >
                    <div className="flex flex-col font-['Pretendard:SemiBold',sans-serif] justify-center leading-[0] not-italic relative shrink-0 text-[#4c5561] text-[14px] text-nowrap">
                      <p className="leading-[1.5] whitespace-pre">{header || `열 ${index + 1}`}</p>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* 데이터 행 */}
            {rows.map((row, rowIndex) => (
              <div
                key={rowIndex}
                className="border-[#dee1e6] border-[1px_0px_0px] border-solid h-[48px] relative shrink-0 w-full"
              >
                <div className="content-stretch flex h-[48px] items-start overflow-clip relative rounded-[inherit] w-full">
                  {headers.map((_, colIndex) => {
                    const isLast = colIndex === headers.length - 1;
                    const cellValue = row[colIndex] || '';
                    return (
                      <div
                        key={colIndex}
                        className={`border-[#dee1e6] ${
                          isLast ? '' : 'border-[0px_1px_0px_0px]'
                        } border-solid box-border content-stretch flex flex-col gap-[4px] ${
                          colIndex === 0 
                            ? 'items-center justify-center w-[48px] px-[8px] py-[12px]' 
                            : 'items-center min-h-px min-w-px px-[8px] py-[12px]'
                        } ${
                          colIndex === 1 ? 'basis-0 grow' : ''
                        } relative shrink-0`}
                      >
                        <p className="font-['Pretendard:Medium',sans-serif] leading-[1.5] not-italic relative shrink-0 text-[#1b2027] text-[15px] text-nowrap whitespace-pre">
                          {cellValue}
                        </p>
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 데이터가 없을 때 */}
      {csvData.length === 0 && (
        <div className="w-full rounded-[8px] border border-[#dee1e6] bg-white min-h-[200px] flex items-center justify-center">
          <p className="text-[16px] font-medium leading-[1.5] text-[#333c47]">
            CSV 파일을 선택하면 표 형태로 표시됩니다.
          </p>
        </div>
      )}
    </div>
  );
}

