import React, {useEffect, useState} from 'react';
import {Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle} from '@/components/ui/dialog';
import {Button} from '@/components/ui/button';
import {Input} from '@/components/ui/input';
import {Label} from '@/components/ui/label';
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from '@/components/ui/select';
import ErrorAlertDialog from '@/components/shared/ErrorAlertDialog';
import {useAPI} from '@/providers/APIProvider';

const AddAPIDialog = ({open, onOpenChange, onSubmit, selectedCollection}) => {
  const {collections, loadCollections} = useAPI();
  const [formData, setFormData] = useState({
    name: '',
    type: '',
    collectionId: '',
  });
  const [error, setError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showErrorDialog, setShowErrorDialog] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);


  useEffect(() => {
    if (selectedCollection?.id) {
      setFormData(prev => ({
        ...prev,
        collectionId: selectedCollection.id
      }));
    }
  }, [selectedCollection]);

  useEffect(() => {
    if (open && !isInitialized) {
      loadCollections();
      setIsInitialized(true);
    }
  }, [open, isInitialized, loadCollections]);

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!formData.name.trim()) {
      setError('API 이름을 입력해주세요');
      return;
    }

    if (!formData.type) {
      setError('API 유형을 선택해주세요');
      return;
    }

    if (!formData.collectionId) {
      setError('컬렉션을 선택해주세요');
      return;
    }

    setIsSubmitting(true);
    try {
      const success = await onSubmit(formData.collectionId, {
        name: formData.name.trim(),
        type: formData.type
      });
      if (success) {
        setFormData({name: '', type: '', collectionId: ''});
        setError('');
        onOpenChange(false);
      } else {
        setError('API 생성에 실패했습니다');
        setShowErrorDialog(true);
      }
    } catch (err) {
      setError(err.message || 'API 생성에 실패했습니다');
      setShowErrorDialog(true);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleOpenChange = (open) => {
    if (!open) {
      setFormData({
        name: '',
        type: '',
        collectionId: selectedCollection?.id || ''  // selectedCollection이 있다면 유지
      });
      setError('');
      setIsInitialized(false); // Dialog가 닫힐 때 초기화 상태를 리셋
    }
    onOpenChange(open);
  };

  return (
      <>
        <Dialog open={open} onOpenChange={handleOpenChange}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>새 API 추가</DialogTitle>
              <DialogDescription>
                새로운 API의 정보를 입력해주세요
              </DialogDescription>
            </DialogHeader>
            <form onSubmit={handleSubmit}>
              <div className="grid gap-4 py-4">
                <div className="grid gap-2">
                  <Label htmlFor="collection">컬렉션</Label>
                  <Select
                      value={formData.collectionId}
                      onValueChange={(value) =>
                          setFormData(prev => ({...prev, collectionId: value}))
                      }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="컬렉션을 선택하세요"/>
                    </SelectTrigger>
                    <SelectContent>
                      {collections.map((collection) => (
                          <SelectItem key={collection.id} value={collection.id}>
                            {collection.name}
                          </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="type">API 유형</Label>
                  <Select
                      value={formData.type}
                      onValueChange={(value) =>
                          setFormData(prev => ({...prev, type: value}))
                      }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="API 유형을 선택하세요"/>
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="HTTP">HTTP</SelectItem>
                      <SelectItem value="HTTPFlat">HTTP Flat</SelectItem>
                      <SelectItem value="TCP">TCP</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="name">API 이름</Label>
                  <Input
                      id="name"
                      value={formData.name}
                      onChange={(e) => {
                        setFormData(prev => ({...prev, name: e.target.value}));
                        setError('');
                      }}
                      placeholder="API 이름을 입력하세요"
                  />
                </div>
              </div>
              <DialogFooter>
                <Button
                    type="button"
                    variant="outline"
                    onClick={() => handleOpenChange(false)}
                    disabled={isSubmitting}
                >
                  취소
                </Button>
                <Button
                    type="submit"
                    disabled={isSubmitting}
                >
                  {isSubmitting ? '생성 중...' : '생성'}
                </Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>

        <ErrorAlertDialog
            open={showErrorDialog}
            onOpenChange={setShowErrorDialog}
            title="API 생성 오류"
            description={error}
        />
      </>
  );
};

export default AddAPIDialog;
