import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  Field,
  FieldDescription,
  FieldGroup,
  FieldLabel,
  FieldSeparator,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { useRouter } from "next/navigation"
import { Loader2, CheckCircle2, XCircle, ChevronLeft, ChevronRight, ChevronDown, Eye, EyeOff } from "lucide-react"
import { SignupFormData } from "@/types/auth.types"
import { Dispatch, SetStateAction, useState } from "react"

interface SignupFormProps extends React.ComponentProps<"form"> {
  onSubmit: (e: React.FormEvent) => void;
  formData: SignupFormData;
  setFormData: Dispatch<SetStateAction<SignupFormData>>;
  error?: string;
  isLoading?: boolean;
  onSendVerificationCode: () => void;
  isEmailVerified: boolean;
  isSendingCode: boolean;
  isCodeSent: boolean;
  verificationCode: string;
  setVerificationCode: (code: string) => void;
  onVerifyCode: () => void;
  isVerifyingCode: boolean;
  emailCheckStatus: 'idle' | 'checking' | 'available' | 'unavailable';
  emailCheckMessage: string;
  currentStep: number;
  setCurrentStep: Dispatch<SetStateAction<number>>;
}

const TOTAL_STEPS = 3;

export function SignupForm({
  className,
  onSubmit,
  formData,
  setFormData,
  error,
  isLoading,
  onSendVerificationCode,
  isEmailVerified,
  isSendingCode,
  isCodeSent,
  verificationCode,
  setVerificationCode,
  onVerifyCode,
  isVerifyingCode,
  emailCheckStatus,
  emailCheckMessage,
  currentStep,
  setCurrentStep,
  ...props
}: SignupFormProps) {
  const router = useRouter();
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);

  const handleChange = (field: keyof SignupFormData, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const emailDomains = [
    'gmail.com',
    'naver.com',
    'daum.net',
    'hanmail.net',
    'nate.com',
    'kakao.com',
    '직접입력',
  ];

  const canGoNext = () => {
    switch (currentStep) {
      case 1:
        return formData.userSe && formData.userId.length >= 4 && formData.userName.length >= 2;
      case 2:
        return isEmailVerified;
      case 3:
        return formData.userPhone && formData.userPassword.length >= 8 && formData.userPassword === formData.confirmPassword;
      default:
        return false;
    }
  };

  const handleNext = () => {
    if (currentStep < TOTAL_STEPS && canGoNext()) {
      setCurrentStep(prev => prev + 1);
    }
  };

  const handlePrev = () => {
    if (currentStep > 1) {
      setCurrentStep(prev => prev - 1);
    }
  };

  const getStepTitle = () => {
    switch (currentStep) {
      case 1:
        return "기본 정보";
      case 2:
        return "이메일 인증";
      case 3:
        return "추가 정보";
      default:
        return "";
    }
  };

  return (
    <form className={cn("flex flex-col gap-3 lg:gap-4", className)} onSubmit={onSubmit} {...props}>
      <FieldGroup>
        {/* 헤더 */}
        <div className="flex flex-col items-center gap-0.5 lg:gap-1 text-center mb-2">
          <h1 className="text-lg lg:text-2xl font-bold">회원가입</h1>
          <p className="text-muted-foreground text-xs lg:text-sm">
            {getStepTitle()}
          </p>
        </div>

        {/* 진행률 표시 */}
        <div className="flex items-center justify-center gap-2 py-2">
          {[1, 2, 3].map((step) => (
            <div key={step} className="flex items-center">
              <div
                className={cn(
                  "w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",
                  currentStep === step
                    ? "bg-primary text-primary-foreground"
                    : currentStep > step
                      ? "bg-primary/20 text-primary"
                      : "bg-gray-300 text-gray-500"
                )}
              >
                {currentStep > step ? <CheckCircle2 className="w-4 h-4" /> : step}
              </div>
              {step < 3 && (
                <div
                  className={cn(
                    "w-8 h-0.5 mx-1",
                    currentStep > step ? "bg-primary/20" : "bg-gray-300"
                  )}
                />
              )}
            </div>
          ))}
        </div>

        {/* Step 1: 기본 정보 */}
        {currentStep === 1 && (
          <>
            <Field>
              <FieldLabel htmlFor="userSe" className="text-sm lg:text-base">회원 유형 *</FieldLabel>
              <Select
                value={formData.userSe}
                onValueChange={(value) => handleChange('userSe', value)}
                disabled={isLoading}
                required
              >
                <SelectTrigger className="h-10 lg:h-11 w-full">
                  <SelectValue placeholder="회원 유형을 선택하세요" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="FARM">농가</SelectItem>
                  <SelectItem value="CNSLT">컨설턴트</SelectItem>
                  <SelectItem value="ORGAN">기관</SelectItem>
                </SelectContent>
              </Select>
            </Field>

            <Field>
              <FieldLabel htmlFor="userId" className="text-sm lg:text-base">아이디 *</FieldLabel>
              <Input
                id="userId"
                type="text"
                value={formData.userId}
                onChange={(e) => handleChange('userId', e.target.value)}
                placeholder="아이디를 입력하세요 (4자 이상)"
                disabled={isLoading}
                required
                className="h-10 lg:h-11"
              />
            </Field>

            <Field>
              <FieldLabel htmlFor="userName" className="text-sm lg:text-base">이름 *</FieldLabel>
              <Input
                id="userName"
                type="text"
                value={formData.userName}
                onChange={(e) => handleChange('userName', e.target.value)}
                placeholder="이름을 입력하세요 (2자 이상)"
                disabled={isLoading}
                required
                className="h-10 lg:h-11"
              />
            </Field>
          </>
        )}

        {/* Step 2: 이메일 인증 */}
        {currentStep === 2 && (
          <>
            <Field>
              <FieldLabel htmlFor="userEmail" className="text-sm lg:text-base">이메일 *</FieldLabel>
              <div className="flex gap-2 items-center">
                <Input
                  id="emailId"
                  type="text"
                  value={formData.emailId}
                  onChange={(e) => {
                    const newEmailId = e.target.value;
                    setFormData((prev) => {
                      const domain = prev.emailDomain === '직접입력' ? prev.customDomain : prev.emailDomain;
                      return {
                        ...prev,
                        emailId: newEmailId,
                        userEmail: domain ? `${newEmailId}@${domain}` : newEmailId,
                      };
                    });
                  }}
                  placeholder="이메일"
                  disabled={isLoading || isEmailVerified}
                  required
                  className="flex-1 h-10 lg:h-11"
                />
                <span className="text-muted-foreground shrink-0">@</span>
                <div className="flex items-center flex-1 h-10 lg:h-11 border rounded-md focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2">
                  {formData.emailDomain === '직접입력' ? (
                    <Input
                      id="customDomain"
                      type="text"
                      placeholder="도메인 입력"
                      value={formData.customDomain || ''}
                      onChange={(e) => {
                        const newDomain = e.target.value;
                        setFormData((prev) => ({
                          ...prev,
                          customDomain: newDomain,
                          userEmail: `${prev.emailId}@${newDomain}`,
                        }));
                      }}
                      disabled={isLoading || isEmailVerified}
                      required
                      className="flex-1 h-full border-0 focus-visible:ring-0 focus-visible:ring-offset-0 rounded-r-none"
                    />
                  ) : (
                    <span className="flex-1 px-3 text-sm truncate">
                      {formData.emailDomain || <span className="text-muted-foreground">도메인 선택</span>}
                    </span>
                  )}
                  <Select
                    value={formData.emailDomain || undefined}
                    onValueChange={(value) => {
                      if (value !== '직접입력') {
                        setFormData((prev) => ({
                          ...prev,
                          emailDomain: value,
                          customDomain: '',
                          userEmail: `${prev.emailId}@${value}`,
                        }));
                      } else {
                        setFormData((prev) => ({
                          ...prev,
                          emailDomain: value,
                          customDomain: '',
                          userEmail: prev.emailId,
                        }));
                      }
                    }}
                    disabled={isLoading || isEmailVerified}
                  >
                    <SelectTrigger className="w-10 h-full border-0 bg-transparent px-0 focus:ring-0 rounded-l-none justify-center" />
                    <SelectContent>
                      {emailDomains.map((domain) => (
                        <SelectItem key={domain} value={domain}>
                          {domain}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              <Button
                type="button"
                onClick={onSendVerificationCode}
                disabled={
                  !formData.emailId ||
                  (formData.emailDomain === '직접입력' ? !formData.customDomain : !formData.emailDomain) ||
                  isLoading ||
                  isEmailVerified ||
                  isSendingCode ||
                  isCodeSent ||
                  emailCheckStatus === 'unavailable' ||
                  emailCheckStatus === 'checking'
                }
                variant={isCodeSent || isEmailVerified ? "secondary" : "outline"}
                className="w-full h-10 lg:h-11"
              >
                {isSendingCode && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {isEmailVerified ? '인증완료' : isSendingCode ? '발송중...' : isCodeSent ? '발송완료' : '인증번호 발송'}
              </Button>
              {emailCheckMessage && !isEmailVerified && (
                <div className={cn(
                  "flex items-center gap-2 text-sm",
                  emailCheckStatus === 'checking' && "text-muted-foreground",
                  emailCheckStatus === 'available' && "text-green-600",
                  emailCheckStatus === 'unavailable' && "text-red-600"
                )}>
                  {emailCheckStatus === 'checking' && <Loader2 className="h-4 w-4 animate-spin" />}
                  {emailCheckStatus === 'available' && <CheckCircle2 className="h-4 w-4" />}
                  {emailCheckStatus === 'unavailable' && <XCircle className="h-4 w-4" />}
                  <span>{emailCheckMessage}</span>
                </div>
              )}
              {isEmailVerified && (
                <FieldDescription className="text-green-600">
                  이메일 인증이 완료되었습니다.
                </FieldDescription>
              )}
            </Field>

            {!isEmailVerified && isCodeSent && formData.userEmail && (
              <Field>
                <FieldLabel htmlFor="verificationCode" className="text-sm lg:text-base">인증번호</FieldLabel>
                <div className="flex gap-2">
                  <Input
                    id="verificationCode"
                    type="text"
                    value={verificationCode}
                    onChange={(e) => setVerificationCode(e.target.value)}
                    placeholder="인증번호 6자리"
                    disabled={isLoading || isEmailVerified}
                    maxLength={6}
                    className="flex-1 h-10 lg:h-11"
                  />
                  <Button
                    type="button"
                    onClick={onVerifyCode}
                    disabled={!verificationCode || isLoading || isEmailVerified || isVerifyingCode}
                    variant="outline"
                    className="h-10 lg:h-11"
                  >
                    {isVerifyingCode && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                    {isVerifyingCode ? '확인중...' : '확인'}
                  </Button>
                </div>
                <FieldDescription>이메일로 받은 6자리 인증번호를 입력하세요.</FieldDescription>
              </Field>
            )}
          </>
        )}

        {/* Step 3: 추가 정보 */}
        {currentStep === 3 && (
          <>
            <Field>
              <FieldLabel htmlFor="userPhone" className="text-sm lg:text-base">휴대폰 번호 *</FieldLabel>
              <Input
                id="userPhone"
                type="tel"
                value={formData.userPhone}
                onChange={(e) => handleChange('userPhone', e.target.value)}
                placeholder="010-0000-0000"
                disabled={isLoading}
                required
                className="h-10 lg:h-11"
              />
            </Field>

            {formData.userSe !== 'FARM' && formData.userSe && (
              <Field>
                <FieldLabel htmlFor="userInstName" className="text-sm lg:text-base">기관명 *</FieldLabel>
                <Input
                  id="userInstName"
                  type="text"
                  value={formData.userInstName || ''}
                  onChange={(e) => handleChange('userInstName', e.target.value)}
                  placeholder="소속 기관명을 입력하세요"
                  disabled={isLoading}
                  required={formData.userSe !== 'FARM'}
                  className="h-10 lg:h-11"
                />
              </Field>
            )}

            <Field>
              <FieldLabel htmlFor="userPassword" className="text-sm lg:text-base">비밀번호 *</FieldLabel>
              <div className="relative">
                <Input
                  id="userPassword"
                  type={showPassword ? "text" : "password"}
                  value={formData.userPassword}
                  onChange={(e) => handleChange('userPassword', e.target.value)}
                  placeholder="비밀번호를 입력하세요 (8자 이상)"
                  disabled={isLoading}
                  required
                  className="h-10 lg:h-11 pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  tabIndex={-1}
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </Field>

            <Field>
              <FieldLabel htmlFor="confirmPassword" className="text-sm lg:text-base">비밀번호 확인 *</FieldLabel>
              <div className="relative">
                <Input
                  id="confirmPassword"
                  type={showConfirmPassword ? "text" : "password"}
                  value={formData.confirmPassword}
                  onChange={(e) => handleChange('confirmPassword', e.target.value)}
                  placeholder="비밀번호를 다시 입력하세요"
                  disabled={isLoading}
                  required
                  className="h-10 lg:h-11 pr-10"
                />
                <button
                  type="button"
                  onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                  tabIndex={-1}
                >
                  {showConfirmPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
              {formData.confirmPassword && formData.userPassword !== formData.confirmPassword && (
                <FieldDescription className="text-red-600">
                  비밀번호가 일치하지 않습니다.
                </FieldDescription>
              )}
            </Field>
          </>
        )}

        {error && (
          <div className="rounded-md bg-red-50 p-2 lg:p-3 text-xs lg:text-sm text-red-600">
            {error}
          </div>
        )}

        {/* 네비게이션 버튼 */}
        <div className="flex gap-2 pt-2">
          {currentStep > 1 && (
            <Button
              type="button"
              variant="outline"
              onClick={handlePrev}
              disabled={isLoading}
              className="flex-1 h-10 lg:h-11"
            >
              <ChevronLeft className="mr-1 h-4 w-4" />
              이전
            </Button>
          )}

          {currentStep < TOTAL_STEPS ? (
            <Button
              type="button"
              onClick={handleNext}
              disabled={!canGoNext() || isLoading}
              className="flex-1 h-10 lg:h-11"
            >
              다음
              <ChevronRight className="ml-1 h-4 w-4" />
            </Button>
          ) : (
            <Button
              type="submit"
              className="flex-1 h-10 lg:h-11"
              disabled={isLoading || !canGoNext()}
            >
              {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {isLoading ? '회원가입 중...' : '회원가입'}
            </Button>
          )}
        </div>

        <FieldSeparator>또는</FieldSeparator>
        <Field>
          <Button
            variant="outline"
            type="button"
            onClick={() => router.push('/login')}
            disabled={isLoading}
            className="w-full h-10 lg:h-11 border-2 border-primary text-primary hover:bg-primary hover:text-primary-foreground hover:border-transparent transition-all duration-300"
          >
            로그인
          </Button>
        </Field>
      </FieldGroup>
    </form>
  )
}
