import React, { useState, useEffect } 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 ErrorAlertDialog from '@/components/shared/ErrorAlertDialog.jsx';

const RenameCollectionDialog = ({ open, onOpenChange, onSubmit, collection }) => {
  const [collectionName, setCollectionName] = useState('');
  const [error, setError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [showErrorDialog, setShowErrorDialog] = useState(false);

  // Update collection name when collection prop changes or dialog opens
  useEffect(() => {
    if (collection && open) {
      setCollectionName(collection.name || '');
    }
  }, [collection, open]);

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

    if (!collectionName.trim()) {
      setError('컬렉션 이름을 입력해주세요');
      return;
    }

    setIsSubmitting(true);
    try {
      const success = await onSubmit(collection.id, collectionName.trim());
      if (success) {
        setError('');
        onOpenChange(false);
      } else {
        setError('컬렉션 이름 변경에 실패했습니다');
        setShowErrorDialog(true);
      }
    } catch (err) {
      setError(err.message || '컬렉션 이름 변경에 실패했습니다');
      setShowErrorDialog(true);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Reset form when dialog is closed
  const handleOpenChange = (open) => {
    if (!open) {
      setError('');
    }
    onOpenChange(open);
  };

  return (
      <>
        <Dialog open={open} onOpenChange={handleOpenChange}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>컬렉션 이름 변경</DialogTitle>
              <DialogDescription>
                변경할 컬렉션의 새로운 이름을 입력해주세요
              </DialogDescription>
            </DialogHeader>
            <form onSubmit={handleSubmit}>
              <div className="grid gap-4 py-4">
                <div className="grid gap-2">
                  <Label htmlFor="name">컬렉션 이름</Label>
                  <Input
                      id="name"
                      value={collectionName}
                      onChange={(e) => {
                        setCollectionName(e.target.value);
                        setError('');
                      }}
                      placeholder="컬렉션 이름을 입력하세요"
                  />
                </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="컬렉션 이름 변경 오류"
            description={error}
        />
      </>
  );
};

export default RenameCollectionDialog;
