'use client';

import { Plus, Trash2 } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { CurrencyInput } from '@/components/ui/currency-input';
import { FileDropzone } from '@/components/ui/file-dropzone';
import { FileList, type NewFile, type ExistingFile } from '@/components/ui/file-list';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import type { ExpenseReportData, ExpenseReportItem } from './types';
import { CARD_OPTIONS } from './types';
import { formatNumber as formatCurrency } from '@/lib/utils/amount';

interface ExpenseReportFormProps {
  data: ExpenseReportData;
  onChange: (data: ExpenseReportData) => void;
}

export function ExpenseReportForm({ data, onChange }: ExpenseReportFormProps) {
  const handleAddItem = () => {
    const newItem: ExpenseReportItem = {
      id: `item-${Date.now()}`,
      description: '',
      amount: 0,
      note: '',
    };
    onChange({ ...data, items: [...data.items, newItem] });
  };

  const handleRemoveItem = (index: number) => {
    const newItems = data.items.filter((_, i) => i !== index);
    const totalAmount = newItems.reduce((sum, item) => sum + item.amount, 0);
    onChange({ ...data, items: newItems, totalAmount });
  };

  const handleItemChange = (index: number, field: keyof ExpenseReportItem, value: string | number) => {
    const newItems = [...data.items];
    newItems[index] = { ...newItems[index], [field]: value };
    const totalAmount = newItems.reduce((sum, item) => sum + item.amount, 0);
    onChange({ ...data, items: newItems, totalAmount });
  };

  const handleFilesSelect = (files: File[]) => {
    onChange({ ...data, attachments: [...data.attachments, ...files] });
  };

  // 기존 업로드 파일 삭제
  const handleRemoveUploadedFile = (fileId: number) => {
    const updatedFiles = (data.uploadedFiles || []).filter((f) => f.id !== fileId);
    onChange({ ...data, uploadedFiles: updatedFiles });
  };

  // 새 첨부 파일 삭제
  const handleRemoveAttachment = (index: number) => {
    const updatedAttachments = data.attachments.filter((_, i) => i !== index);
    onChange({ ...data, attachments: updatedAttachments });
  };

  return (
    <div className="space-y-6">
      {/* 지출 정보 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">지출 정보</h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="requestDate">지출 요청일</Label>
            <DatePicker
              value={data.requestDate}
              onChange={(date) => onChange({ ...data, requestDate: date })}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="paymentDate">결제일</Label>
            <DatePicker
              value={data.paymentDate}
              onChange={(date) => onChange({ ...data, paymentDate: date })}
            />
          </div>
        </div>
      </div>

      {/* 지출결의서 정보 */}
      <div className="bg-white rounded-lg border p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold">지출결의서 정보</h3>
          <Button variant="outline" size="sm" onClick={handleAddItem}>
            <Plus className="w-4 h-4 mr-1" />
            추가
          </Button>
        </div>

        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[60px] text-center">번호</TableHead>
                <TableHead className="min-w-[200px]">적요</TableHead>
                <TableHead className="min-w-[150px]">금액</TableHead>
                <TableHead className="min-w-[150px]">비고</TableHead>
                <TableHead className="w-[60px] text-center">삭제</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.items.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-8 text-gray-400">
                    항목을 추가해주세요
                  </TableCell>
                </TableRow>
              ) : (
                data.items.map((item, index) => (
                  <TableRow key={item.id}>
                    <TableCell className="text-center">{index + 1}</TableCell>
                    <TableCell>
                      <Input
                        placeholder="적요를 입력해주세요"
                        value={item.description}
                        onChange={(e) => handleItemChange(index, 'description', e.target.value)}
                      />
                    </TableCell>
                    <TableCell>
                      <CurrencyInput
                        placeholder="금액을 입력해주세요"
                        value={item.amount || 0}
                        onChange={(value) => handleItemChange(index, 'amount', value ?? 0)}
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        placeholder="비고를 입력해주세요"
                        value={item.note}
                        onChange={(e) => handleItemChange(index, 'note', e.target.value)}
                      />
                    </TableCell>
                    <TableCell className="text-center">
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 text-red-500 hover:text-red-700 hover:bg-red-50"
                        onClick={() => handleRemoveItem(index)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      {/* 결제 정보 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">결제 정보</h3>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <Label htmlFor="card">카드</Label>
            <Select
              value={data.cardId}
              onValueChange={(value) => onChange({ ...data, cardId: value })}
            >
              <SelectTrigger>
                <SelectValue placeholder="카드를 선택해주세요" />
              </SelectTrigger>
              <SelectContent>
                {CARD_OPTIONS.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label>총 비용</Label>
            <div className="h-10 px-3 py-2 bg-gray-50 border rounded-md text-right font-semibold">
              {formatCurrency(data.totalAmount)}원
            </div>
          </div>
        </div>
      </div>

      {/* 참고 이미지 정보 */}
      <div className="bg-white rounded-lg border p-6">
        <h3 className="text-lg font-semibold mb-4">참고 이미지 정보</h3>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label>첨부파일</Label>
            <FileDropzone
              onFilesSelect={handleFilesSelect}
              multiple
              accept="image/*"
              maxSize={10}
              compact
              title="클릭하거나 파일을 드래그하세요"
              description="이미지 파일만 업로드 가능합니다"
            />
          </div>

          {/* 파일 목록 */}
          <FileList
            files={data.attachments.map((file): NewFile => ({ file }))}
            existingFiles={(data.uploadedFiles || []).map((file): ExistingFile => ({
              id: file.id,
              name: file.name,
              url: file.url,
              size: file.size,
            }))}
            onRemove={handleRemoveAttachment}
            onRemoveExisting={(id) => handleRemoveUploadedFile(id as number)}
            emptyMessage="첨부된 파일이 없습니다"
            compact
          />
        </div>
      </div>
    </div>
  );
}