'use client';

import { useState, useCallback } from 'react';
import { toast } from 'sonner';
import { Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { BANK_OPTIONS, ACCOUNT_TYPE_OPTIONS } from './types';
import type { BankServiceFormData } from './types';
import { getBankServiceUrl } from './actions';

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

export function BankServiceModal({ open, onOpenChange }: BankServiceModalProps) {
  const [formData, setFormData] = useState<BankServiceFormData>({
    bankCode: BANK_OPTIONS[0].value,
    accountType: ACCOUNT_TYPE_OPTIONS[0].value,
  });
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleOpenChange = useCallback((isOpen: boolean) => {
    if (isOpen) {
      setFormData({
        bankCode: BANK_OPTIONS[0].value,
        accountType: ACCOUNT_TYPE_OPTIONS[0].value,
      });
    }
    onOpenChange(isOpen);
  }, [onOpenChange]);

  const handleSubmit = useCallback(async () => {
    setIsSubmitting(true);
    try {
      const result = await getBankServiceUrl(formData);
      if (result.success && result.data?.url) {
        window.open(result.data.url, '_blank');
        onOpenChange(false);
      } else {
        toast.error(result.error || '서비스 URL 조회에 실패했습니다.');
      }
    } catch {
      toast.error('서비스 URL 조회 중 오류가 발생했습니다.');
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, onOpenChange]);

  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">
          {/* 은행 Select */}
          <div>
            <Label className="text-sm font-medium">
              은행 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={formData.bankCode}
              onValueChange={(v) => setFormData(prev => ({ ...prev, bankCode: v }))}
            >
              <SelectTrigger className="mt-1">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {BANK_OPTIONS.map(opt => (
                  <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* 구분 Select */}
          <div>
            <Label className="text-sm font-medium">
              구분 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={formData.accountType}
              onValueChange={(v) => setFormData(prev => ({ ...prev, accountType: v }))}
            >
              <SelectTrigger className="mt-1">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {ACCOUNT_TYPE_OPTIONS.map(opt => (
                  <SelectItem key={opt.value} value={opt.value}>{opt.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        </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>
  );
}
