'use client';

import { useRef } from 'react';
import { Mic, Upload, X, FileText, ExternalLink } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { CurrencyInput } from '@/components/ui/currency-input';
import { Textarea } from '@/components/ui/textarea';
import type { ProposalData, UploadedFile } from './types';

interface ProposalFormProps {
  data: ProposalData;
  onChange: (data: ProposalData) => void;
}

export function ProposalForm({ data, onChange }: ProposalFormProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files) {
      onChange({ ...data, attachments: [...data.attachments, ...Array.from(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="vendor">구매처</Label>
            <Input
              id="vendor"
              placeholder="구매처를 입력해주세요"
              value={data.vendor}
              onChange={(e) => onChange({ ...data, vendor: e.target.value })}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="vendorPaymentDate">구매처 결제일</Label>
            <Input
              id="vendorPaymentDate"
              type="date"
              value={data.vendorPaymentDate}
              onChange={(e) => onChange({ ...data, vendorPaymentDate: e.target.value })}
            />
          </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 htmlFor="title">제목</Label>
            <Input
              id="title"
              placeholder="제목을 입력해주세요"
              value={data.title}
              onChange={(e) => onChange({ ...data, title: e.target.value })}
            />
          </div>

          {/* 품의 내역 */}
          <div className="space-y-2">
            <Label htmlFor="description">품의 내역</Label>
            <div className="relative">
              <Textarea
                id="description"
                placeholder="품의 내역을 입력해주세요"
                value={data.description}
                onChange={(e) => onChange({ ...data, description: e.target.value })}
                className="min-h-[100px] pr-12"
              />
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="absolute right-2 bottom-2"
                title="녹음"
              >
                <Mic className="w-4 h-4" />
                녹음
              </Button>
            </div>
          </div>

          {/* 품의 사유 */}
          <div className="space-y-2">
            <Label htmlFor="reason">품의 사유</Label>
            <div className="relative">
              <Textarea
                id="reason"
                placeholder="품의 사유를 입력해주세요"
                value={data.reason}
                onChange={(e) => onChange({ ...data, reason: e.target.value })}
                className="min-h-[100px] pr-12"
              />
              <Button
                type="button"
                variant="outline"
                size="sm"
                className="absolute right-2 bottom-2"
                title="녹음"
              >
                <Mic className="w-4 h-4" />
                녹음
              </Button>
            </div>
          </div>

          {/* 예상 비용 */}
          <div className="space-y-2">
            <Label htmlFor="estimatedCost">예상 비용</Label>
            <CurrencyInput
              id="estimatedCost"
              placeholder="금액을 입력해주세요"
              value={data.estimatedCost || 0}
              onChange={(value) => onChange({ ...data, estimatedCost: value ?? 0 })}
            />
          </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>
            <div className="flex items-center gap-2">
              <input
                ref={fileInputRef}
                type="file"
                multiple
                className="hidden"
                onChange={handleFileChange}
                accept="image/*"
              />
              <Button
                type="button"
                variant="outline"
                onClick={() => fileInputRef.current?.click()}
              >
                <Upload className="w-4 h-4 mr-2" />
                파일 추가
              </Button>
            </div>
          </div>

          {/* 기존 업로드된 파일 목록 */}
          {data.uploadedFiles && data.uploadedFiles.length > 0 && (
            <div className="space-y-2">
              <Label className="text-sm text-gray-600">저장된 파일</Label>
              <div className="space-y-2">
                {data.uploadedFiles.map((file) => (
                  <div
                    key={file.id}
                    className="flex items-center justify-between gap-2 p-2 bg-gray-50 rounded-md"
                  >
                    <div className="flex items-center gap-2 flex-1 min-w-0">
                      <FileText className="w-4 h-4 text-gray-500 flex-shrink-0" />
                      <span className="text-sm truncate">{file.name}</span>
                      {file.size && (
                        <span className="text-xs text-gray-400 flex-shrink-0">
                          ({Math.round(file.size / 1024)}KB)
                        </span>
                      )}
                    </div>
                    <div className="flex items-center gap-1 flex-shrink-0">
                      {file.url && (
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => window.open(file.url, '_blank')}
                          title="파일 보기"
                        >
                          <ExternalLink className="w-4 h-4" />
                        </Button>
                      )}
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => handleRemoveUploadedFile(file.id)}
                        title="파일 삭제"
                        className="text-red-500 hover:text-red-700"
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 새로 추가할 파일 목록 */}
          {data.attachments.length > 0 && (
            <div className="space-y-2">
              <Label className="text-sm text-gray-600">새로 추가할 파일</Label>
              <div className="space-y-2">
                {data.attachments.map((file, index) => (
                  <div
                    key={`new-${index}`}
                    className="flex items-center justify-between gap-2 p-2 bg-blue-50 rounded-md"
                  >
                    <div className="flex items-center gap-2 flex-1 min-w-0">
                      <FileText className="w-4 h-4 text-blue-500 flex-shrink-0" />
                      <span className="text-sm truncate">{file.name}</span>
                      <span className="text-xs text-gray-400 flex-shrink-0">
                        ({Math.round(file.size / 1024)}KB)
                      </span>
                    </div>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => handleRemoveAttachment(index)}
                      title="파일 삭제"
                      className="text-red-500 hover:text-red-700 flex-shrink-0"
                    >
                      <X className="w-4 h-4" />
                    </Button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 파일이 없을 때 안내 메시지 */}
          {(!data.uploadedFiles || data.uploadedFiles.length === 0) && data.attachments.length === 0 && (
            <div className="text-sm text-gray-500 text-center py-4 border border-dashed rounded-md">
              첨부된 파일이 없습니다. 위 버튼을 클릭하여 파일을 추가하세요.
            </div>
          )}
        </div>
      </div>
    </div>
  );
}