'use client';

import { useState, useCallback } from 'react';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { FormField } from '@/components/molecules/FormField';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import type { BarobillLoginFormData } from './types';
import { registerBarobillLogin } from './actions';

interface LoginModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

const initialFormData: BarobillLoginFormData = {
  barobillId: '',
  password: '',
};

export function LoginModal({ open, onOpenChange, onSuccess }: LoginModalProps) {
  const [formData, setFormData] = useState<BarobillLoginFormData>(initialFormData);
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleOpenChange = useCallback((isOpen: boolean) => {
    if (isOpen) setFormData(initialFormData);
    onOpenChange(isOpen);
  }, [onOpenChange]);

  const handleChange = useCallback((key: keyof BarobillLoginFormData, value: string) => {
    setFormData(prev => ({ ...prev, [key]: value }));
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!formData.barobillId) {
      toast.error('바로빌 아이디를 입력해주세요.');
      return;
    }
    if (!formData.password) {
      toast.error('비밀번호를 입력해주세요.');
      return;
    }

    setIsSubmitting(true);
    try {
      const result = await registerBarobillLogin(formData);
      if (result.success) {
        toast.success('바로빌 로그인 정보가 등록되었습니다.');
        onOpenChange(false);
        onSuccess();
      } else {
        toast.error(result.error || '등록에 실패했습니다.');
      }
    } catch {
      toast.error('등록 중 오류가 발생했습니다.');
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, onOpenChange, onSuccess]);

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-[450px]" aria-describedby={undefined}>
        <DialogHeader>
          <DialogTitle>바로빌 로그인 정보 등록</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 py-2">
          <FormField
            label="바로빌 아이디"
            required
            value={formData.barobillId}
            onChange={(v) => handleChange('barobillId', v)}
            placeholder="Barobill_id"
          />
          <FormField
            type="password"
            label="비밀번호"
            required
            value={formData.password}
            onChange={(v) => handleChange('password', v)}
          />
        </div>

        <DialogFooter className="gap-3">
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
            취소
          </Button>
          <Button onClick={handleSubmit} disabled={isSubmitting}>
            {isSubmitting ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                등록 중...
              </>
            ) : (
              '등록하기'
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
