'use client';

import { useState } from 'react';
import { uploadBuyerSignature } from './buyer-signature';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Upload, Loader2, CheckCircle } from 'lucide-react';
import { toast } from 'sonner';

export function BuyerSignatureUploadForm() {
  const [isUploading, setIsUploading] = useState(false);
  const [preview, setPreview] = useState<string | null>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => {
        setPreview(reader.result as string);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setIsUploading(true);

    const formData = new FormData(e.currentTarget);
    
    try {
      const result = await uploadBuyerSignature(formData);
      
      if (result.success) {
        toast.success('서명이 성공적으로 업로드되었습니다.');
        setPreview(null);
        (e.target as HTMLFormElement).reset();
      } else {
        toast.error(result.error || '업로드에 실패했습니다.');
      }
    } catch (error) {
      toast.error('업로드 중 오류가 발생했습니다.');
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle>구매자 서명 업로드</CardTitle>
        <CardDescription>
          삼성중공업 서명 이미지를 업로드하세요. 이 서명은 계약서에 자동으로 적용됩니다.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="file">서명 이미지</Label>
            <Input
              id="file"
              name="file"
              type="file"
              accept="image/*"
              onChange={handleFileChange}
              required
              disabled={isUploading}
            />
            <p className="text-sm text-muted-foreground">
              PNG, JPG, JPEG 형식 (최대 5MB)
            </p>
          </div>

          {preview && (
            <div className="border rounded-lg p-4 bg-gray-50">
              <Label className="text-sm font-medium mb-2 block">미리보기</Label>
              <img 
                src={preview} 
                alt="서명 미리보기" 
                className="max-h-32 object-contain"
              />
            </div>
          )}

          <Alert>
            <AlertDescription>
              업로드한 서명은 즉시 활성화되며, 새로운 계약서에 자동으로 적용됩니다.
            </AlertDescription>
          </Alert>

          <Button 
            type="submit" 
            disabled={isUploading || !preview}
            className="w-full"
          >
            {isUploading ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                업로드 중...
              </>
            ) : (
              <>
                <Upload className="mr-2 h-4 w-4" />
                서명 업로드
              </>
            )}
          </Button>
        </form>
      </CardContent>
    </Card>
  );
}