import { useState, useCallback } from 'react';
import { LoginCredentials, RegisterData } from '@/types';
import { useTranslation } from 'react-i18next';
import { t } from 'i18next';

interface FormErrors {
  email?: string;
  password?: string;
  name?: string;
  phone?: string;
  confirmPassword?: string;
  general?: string;
}

interface UseLoginFormReturn {
  formData: LoginCredentials;
  errors: FormErrors;
  isLoading: boolean;
  handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  handleSubmit: (onSubmit: (data: LoginCredentials) => Promise<void>) => (e: React.FormEvent) => Promise<void>;
  resetForm: () => void;
  setError: (field: keyof FormErrors, message: string) => void;
  clearErrors: () => void;
}

interface UseRegisterFormReturn {
  formData: RegisterData & { confirmPassword: string };
  errors: FormErrors;
  isLoading: boolean;
  handleChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  handleSubmit: (onSubmit: (data: RegisterData) => Promise<void>) => (e: React.FormEvent) => Promise<void>;
  resetForm: () => void;
  setError: (field: keyof FormErrors, message: string) => void;
  clearErrors: () => void;
}

export const useLoginForm = (): UseLoginFormReturn => {
  const { t } = useTranslation();
  const [formData, setFormData] = useState<LoginCredentials>({
    email: '',
    password: '',
  });
  const [errors, setErrors] = useState<FormErrors>({});
  const [isLoading, setIsLoading] = useState(false);

  const validateLoginForm = useCallback((data: LoginCredentials): FormErrors => {
    const newErrors: FormErrors = {};

    if (!data.email.trim()) {
      newErrors.email = t('login.emailPlaceholder');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
      newErrors.email = t('login.emailPlaceholder');
    }

    if (!data.password.trim()) {
      newErrors.password = t('login.passwordPlaceholder');
    } else if (data.password.length < 6) {
      newErrors.password = t('login.passwordMinLength');
    }

    return newErrors;
  }, [t]);

  const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // 해당 필드의 에러 제거
    if (errors[name as keyof FormErrors]) {
      setErrors(prev => ({ ...prev, [name]: undefined }));
    }
  }, [errors]);

  const handleSubmit = useCallback((onSubmit: (data: LoginCredentials) => Promise<void>) => {
    return async (e: React.FormEvent) => {
      e.preventDefault();
      
      const validationErrors = validateLoginForm(formData);
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        return;
      }

      setIsLoading(true);
      setErrors({});

      try {
        await onSubmit(formData);
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : t('login.generalError');
        setErrors({ general: errorMessage });
      } finally {
        setIsLoading(false);
      }
    };
  }, [formData, validateLoginForm, t]);

  const resetForm = useCallback(() => {
    setFormData({ email: '', password: '' });
    setErrors({});
    setIsLoading(false);
  }, []);

  const setError = useCallback((field: keyof FormErrors, message: string) => {
    setErrors(prev => ({ ...prev, [field]: message }));
  }, []);

  const clearErrors = useCallback(() => {
    setErrors({});
  }, []);

  return {
    formData,
    errors,
    isLoading,
    handleChange,
    handleSubmit,
    resetForm,
    setError,
    clearErrors,
  };
};

export const useRegisterForm = (): UseRegisterFormReturn => {
  const [formData, setFormData] = useState<RegisterData & { confirmPassword: string }>({
    email: '',
    password: '',
    name: '',
    phone: '',
    confirmPassword: '',
  });
  const [errors, setErrors] = useState<FormErrors>({});
  const [isLoading, setIsLoading] = useState(false);

  const validateRegisterForm = useCallback((data: RegisterData & { confirmPassword: string }): FormErrors => {
    const newErrors: FormErrors = {};

    if (!data.email.trim()) {
      newErrors.email = '이메일을 입력해주세요.';
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
      newErrors.email = '올바른 이메일 형식을 입력해주세요.';
    }

    if (!data.password.trim()) {
      newErrors.password = t('login.passwordPlaceholder');
    } else if (data.password.length < 8) {
      newErrors.password = t('login.passwordMinLength');
    } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(data.password)) {
      newErrors.password = t('login.passwordComplexity');
    }

    if (!data.confirmPassword.trim()) {
      newErrors.confirmPassword = t('login.confirmPasswordPlaceholder');
    } else if (data.password !== data.confirmPassword) {
      newErrors.confirmPassword = t('login.confirmPasswordMismatch');
    }

    if (!data.name.trim()) {
      newErrors.name = t('login.namePlaceholder');
    } else if (data.name.length < 2) {
      newErrors.name = t('login.nameMinLength');
    }

    if (data.phone && !/^[0-9-+\s()]+$/.test(data.phone)) {
      newErrors.phone = t('login.phoneFormat');
    }

    return newErrors;
  }, []);

  const handleChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // 해당 필드의 에러 제거
    if (errors[name as keyof FormErrors]) {
      setErrors(prev => ({ ...prev, [name]: undefined }));
    }
  }, [errors]);

  const handleSubmit = useCallback((onSubmit: (data: RegisterData) => Promise<void>) => {
    return async (e: React.FormEvent) => {
      e.preventDefault();
      
      const validationErrors = validateRegisterForm(formData);
      if (Object.keys(validationErrors).length > 0) {
        setErrors(validationErrors);
        return;
      }

      setIsLoading(true);
      setErrors({});

      try {
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        const { confirmPassword: _confirmPassword, ...registerData } = formData;
        await onSubmit(registerData);
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : '회원가입 중 오류가 발생했습니다.';
        setErrors({ general: errorMessage });
      } finally {
        setIsLoading(false);
      }
    };
  }, [formData, validateRegisterForm]);

  const resetForm = useCallback(() => {
    setFormData({
      email: '',
      password: '',
      name: '',
      phone: '',
      confirmPassword: '',
    });
    setErrors({});
    setIsLoading(false);
  }, []);

  const setError = useCallback((field: keyof FormErrors, message: string) => {
    setErrors(prev => ({ ...prev, [field]: message }));
  }, []);

  const clearErrors = useCallback(() => {
    setErrors({});
  }, []);

  return {
    formData,
    errors,
    isLoading,
    handleChange,
    handleSubmit,
    resetForm,
    setError,
    clearErrors,
  };
};