'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import { z } from 'zod';
import {
  Box,
  TextField,
  Button,
  Typography,
  Paper,
  LinearProgress,
  IconButton,
  InputAdornment,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Checkbox,
  FormControlLabel,
  FormGroup,
  Link,
  Dialog,
  DialogContent,
  DialogActions,
} from '@mui/material';
import { ArrowBack, Visibility, VisibilityOff, CheckCircle } from '@mui/icons-material';
import { useState, useEffect, Suspense } from 'react';
import { useUIStore } from '@/stores/uiStore';
import { useAuthContext } from '@/features/auth';
import { getGradientButtonStyle, responsiveText } from '@/shared/lib/button-styles';

// 각 단계별 유효성 검사 스키마
const step1Schema = z
  .object({
    email: z.string().min(1, '이메일을 입력해주세요').email('올바른 이메일 형식이 아닙니다'),
    password: z
      .string()
      .min(8, '비밀번호는 8자 이상이어야 합니다')
      .max(100, '비밀번호는 100자 이하여야 합니다'),
    confirmPassword: z.string().min(1, '비밀번호 확인을 입력해주세요'),
  })
  .refine((data) => data.password === data.confirmPassword, {
    message: '비밀번호가 일치하지 않습니다',
    path: ['confirmPassword'],
  });

const step2Schema = z.object({
  name: z.string().min(2, '이름은 2자 이상이어야 합니다').max(50, '이름은 50자 이하여야 합니다'),
  phone: z
    .string()
    .min(1, '휴대폰 번호를 입력해주세요')
    .regex(/^010-\d{4}-\d{4}$/, '올바른 휴대폰 번호 형식이 아닙니다 (010-1234-5678)'),
});

const step3Schema = z.object({
  businessName: z.string().min(2, '상호명은 2자 이상이어야 합니다').max(100, '상호명은 100자 이하여야 합니다'),
  businessNumber: z
    .string()
    .min(1, '사업자 번호를 입력해주세요')
    .regex(/^\d{3}-\d{2}-\d{5}$/, '올바른 사업자 번호 형식이 아닙니다 (123-45-67890)'),
  businessType: z.string().min(1, '업종을 선택해주세요').max(50, '업종은 50자 이하여야 합니다'),
  businessLocation: z.string().max(255, '주소는 255자 이하여야 합니다').optional(),
  businessHours: z.string().max(255, '영업시간은 255자 이하여야 합니다').optional(),
  agreeTerms: z.boolean().refine((val) => val === true, {
    message: '이용약관에 동의해주세요',
  }),
  agreePrivacy: z.boolean().refine((val) => val === true, {
    message: '개인정보 처리방침에 동의해주세요',
  }),
  agreeMarketing: z.boolean().optional(),
});

type Step1Data = z.infer<typeof step1Schema>;
type Step2Data = z.infer<typeof step2Schema>;
type Step3Data = z.infer<typeof step3Schema>;

type RegisterData = Step1Data & Step2Data & Step3Data;

function RegisterForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { showToast, setLoading } = useUIStore();
  const { register: registerUser } = useAuthContext();

  // URL 쿼리에서 step 파라미터 읽기 (기본값: 1)
  const stepParam = searchParams.get('step');
  const initialStep = stepParam ? parseInt(stepParam) : 1;

  const [currentStep, setCurrentStep] = useState<number>(initialStep);
  const [formData, setFormData] = useState<Partial<RegisterData>>({
    agreeMarketing: false,
  });
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [isVerifyingBusinessNumber, setIsVerifyingBusinessNumber] = useState(false);
  const [isBusinessNumberVerified, setIsBusinessNumberVerified] = useState(false);
  const [successDialogOpen, setSuccessDialogOpen] = useState(false);

  // step 변경 시 URL 업데이트
  useEffect(() => {
    const newStep = Math.max(1, Math.min(3, currentStep));
    if (newStep !== currentStep) {
      setCurrentStep(newStep);
    }
    router.replace(`/register?step=${newStep}`, { scroll: false });
  }, [currentStep, router]);

  const formatPhoneNumber = (value: string) => {
    const numbers = value.replace(/[^\d]/g, '');
    if (numbers.length <= 3) return numbers;
    if (numbers.length <= 7) return `${numbers.slice(0, 3)}-${numbers.slice(3)}`;
    return `${numbers.slice(0, 3)}-${numbers.slice(3, 7)}-${numbers.slice(7, 11)}`;
  };

  const formatBusinessNumber = (value: string) => {
    const numbers = value.replace(/[^\d]/g, '');
    if (numbers.length <= 3) return numbers;
    if (numbers.length <= 5) return `${numbers.slice(0, 3)}-${numbers.slice(3)}`;
    return `${numbers.slice(0, 3)}-${numbers.slice(3, 5)}-${numbers.slice(5, 10)}`;
  };

  const handleVerifyBusinessNumber = async () => {
    if (!formData.businessNumber) {
      showToast('사업자 번호를 입력해주세요', 'error');
      return;
    }

    if (!/^\d{3}-\d{2}-\d{5}$/.test(formData.businessNumber)) {
      showToast('올바른 사업자 번호 형식이 아닙니다', 'error');
      return;
    }

    setIsVerifyingBusinessNumber(true);

    try {
      // TODO: API 연동 시 실제 사업자 번호 검증 API 호출
      // const response = await axios.post(`${BUSINESS_HOST}/api/v1/business/verify`, {
      //   businessNumber: formData.businessNumber
      // });

      // 임시 처리: 2초 후 성공
      await new Promise((resolve) => setTimeout(resolve, 2000));

      setIsBusinessNumberVerified(true);
      showToast('사업자 번호 인증이 완료되었습니다', 'success');
    } catch {
      setIsBusinessNumberVerified(false);
      showToast('사업자 번호 인증에 실패했습니다', 'error');
    } finally {
      setIsVerifyingBusinessNumber(false);
    }
  };

  const progress = (currentStep / 3) * 100;

  const validateStep = (step: number) => {
    setErrors({});

    try {
      if (step === 1) {
        step1Schema.parse(formData);
      } else if (step === 2) {
        step2Schema.parse(formData);
      } else if (step === 3) {
        step3Schema.parse(formData);
      }
      return true;
    } catch (error) {
      if (error instanceof z.ZodError) {
        const newErrors: Record<string, string> = {};
        error.errors.forEach((err) => {
          if (err.path[0]) {
            newErrors[err.path[0].toString()] = err.message;
          }
        });
        setErrors(newErrors);

        // 첫 번째 에러 메시지를 Toast로 표시
        const firstError = error.errors[0];
        if (firstError) {
          showToast(firstError.message, 'error');
        }
      }
      return false;
    }
  };

  const handleNext = () => {
    if (!validateStep(currentStep)) {
      return;
    }

    if (currentStep < 3) {
      setCurrentStep(currentStep + 1);
    } else {
      handleSubmit();
    }
  };

  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    } else {
      router.back();
    }
  };

  const handleSubmit = async () => {
    console.log('📝 Step 3 검증 시작');

    if (!validateStep(3)) {
      console.error('❌ Step 3 검증 실패');
      return;
    }

    console.log('✅ Step 3 검증 통과');

    try {
      setLoading(true);
      console.log('🔄 회원가입 프로세스 시작');

      // 전화번호 형식 변환: 010-1234-5678 -> 01012345678
      const phoneNumber = formData.phone!.replace(/-/g, '');
      console.log('📞 전화번호 변환:', formData.phone, '->', phoneNumber);

      // API 요청 데이터 구성
      const registerData = {
        name: formData.name!,
        phoneNumber: phoneNumber,
        email: formData.email!,
        password: formData.password!,
        storeName: formData.businessName!,
        industry: formData.businessType || '',
        address: formData.businessLocation || '',
        businessHours: formData.businessHours || '',
      };

      console.log('📦 회원가입 요청 데이터:', {
        ...registerData,
        password: '***' // 비밀번호는 로그에 표시 안 함
      });

      // User API 호출
      console.log('🚀 registerUser 함수 호출');
      const result = await registerUser(registerData);
      console.log('📥 registerUser 결과:', result);

      if (result.success) {
        console.log('✅ 회원가입 성공:', result.user);
        showToast('회원가입이 완료되었습니다!', 'success');
        setSuccessDialogOpen(true);
      } else {
        console.error('❌ 회원가입 실패:', result.error);
        showToast(result.error || '회원가입에 실패했습니다. 다시 시도해주세요.', 'error');
      }
    } catch (error) {
      console.error('💥 회원가입 예외 발생:', error);
      if (error instanceof Error) {
        console.error('오류 메시지:', error.message);
        console.error('오류 스택:', error.stack);
      }
      showToast('회원가입 중 오류가 발생했습니다. 다시 시도해주세요.', 'error');
    } finally {
      console.log('🏁 회원가입 프로세스 종료');
      setLoading(false);
    }
  };

  const handleSuccessDialogClose = () => {
    setSuccessDialogOpen(false);
    router.push('/');
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        px: 3,
        py: 8,
        background: 'linear-gradient(135deg, #FFF 0%, #F5F5F5 100%)',
      }}
    >
      <Paper
        elevation={0}
        sx={{
          width: '100%',
          maxWidth: 440,
          p: { xs: 4, sm: 6 },
          borderRadius: 3,
          boxShadow: '0 8px 32px rgba(0,0,0,0.08)',
        }}
      >
        {/* Header with back button */}
        <Box sx={{ display: 'flex', alignItems: 'center', mb: 4 }}>
          <IconButton onClick={handleBack} edge="start" sx={{ mr: 2 }}>
            <ArrowBack />
          </IconButton>
          <Typography variant="h6" sx={{ fontWeight: 600 }}>
            회원가입
          </Typography>
        </Box>

        {/* Progress Bar */}
        <Box sx={{ mb: 4 }}>
          <LinearProgress
            variant="determinate"
            value={progress}
            sx={{ height: 6, borderRadius: 3 }}
          />
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1, textAlign: 'center' }}>
            {currentStep}/3 단계
          </Typography>
        </Box>

        {/* Step 1: 계정정보 */}
        {currentStep === 1 && (
          <Box>
            <Typography variant="h5" sx={{ ...responsiveText.h3, mb: 1 }}>
              계정 정보를 입력해주세요
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 4 }}>
              로그인에 사용할 이메일과 비밀번호를 설정합니다
            </Typography>

            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
              <TextField
                fullWidth
                label="이메일"
                type="email"
                placeholder="example@email.com"
                value={formData.email || ''}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                error={!!errors.email}
                helperText={errors.email || '이메일 주소로 로그인합니다'}
                required
              />

              <TextField
                fullWidth
                label="비밀번호"
                type={showPassword ? 'text' : 'password'}
                placeholder="8자 이상"
                value={formData.password || ''}
                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                error={!!errors.password}
                helperText={errors.password || '비밀번호는 8자 이상이어야 합니다'}
                required
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton onClick={() => setShowPassword(!showPassword)} edge="end">
                        {showPassword ? <VisibilityOff /> : <Visibility />}
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
              />

              <TextField
                fullWidth
                label="비밀번호 확인"
                type={showConfirmPassword ? 'text' : 'password'}
                placeholder="비밀번호를 다시 입력하세요"
                value={formData.confirmPassword || ''}
                onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
                error={!!errors.confirmPassword}
                helperText={errors.confirmPassword}
                required
                InputProps={{
                  endAdornment: (
                    <InputAdornment position="end">
                      <IconButton
                        onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                        edge="end"
                      >
                        {showConfirmPassword ? <VisibilityOff /> : <Visibility />}
                      </IconButton>
                    </InputAdornment>
                  ),
                }}
              />

              <Button
                fullWidth
                variant="contained"
                size="large"
                onClick={handleNext}
                sx={{
                  mt: 2,
                  py: { xs: 1.5, sm: 1.75 },
                  fontSize: { xs: 15, sm: 16 },
                  ...getGradientButtonStyle('primary'),
                }}
              >
                다음
              </Button>

              <Box sx={{ textAlign: 'center', mt: 2 }}>
                <Typography variant="body2" color="text.secondary">
                  이미 계정이 있으신가요?{' '}
                  <Link
                    href="/login"
                    underline="hover"
                    sx={{ color: 'primary.main', fontWeight: 600 }}
                  >
                    로그인
                  </Link>
                </Typography>
              </Box>
            </Box>
          </Box>
        )}

        {/* Step 2: 개인정보 */}
        {currentStep === 2 && (
          <Box>
            <Typography variant="h5" sx={{ ...responsiveText.h3, mb: 1 }}>
              개인 정보를 입력해주세요
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 4 }}>
              서비스 이용을 위한 기본 정보입니다
            </Typography>

            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
              <TextField
                fullWidth
                label="이름"
                placeholder="홍길동"
                value={formData.name || ''}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                error={!!errors.name}
                helperText={errors.name}
                required
              />

              <TextField
                fullWidth
                label="휴대폰 번호"
                placeholder="010-1234-5678"
                value={formData.phone || ''}
                onChange={(e) => {
                  const formatted = formatPhoneNumber(e.target.value);
                  setFormData({ ...formData, phone: formatted });
                }}
                error={!!errors.phone}
                helperText={errors.phone}
                required
              />

              <Box sx={{ display: 'flex', gap: 2, mt: 2 }}>
                <Button
                  variant="outlined"
                  size="large"
                  onClick={handleBack}
                  sx={{
                    flex: 1,
                    py: { xs: 1.5, sm: 1.75 },
                    fontSize: { xs: 15, sm: 16 },
                    fontWeight: 600,
                    borderWidth: 2,
                  }}
                >
                  이전
                </Button>
                <Button
                  variant="contained"
                  size="large"
                  onClick={handleNext}
                  sx={{
                    flex: 1,
                    py: { xs: 1.5, sm: 1.75 },
                    fontSize: { xs: 15, sm: 16 },
                    ...getGradientButtonStyle('primary'),
                  }}
                >
                  다음
                </Button>
              </Box>
            </Box>
          </Box>
        )}

        {/* Step 3: 사업장정보 */}
        {currentStep === 3 && (
          <Box>
            <Typography variant="h5" sx={{ ...responsiveText.h3, mb: 1 }}>
              사업장 정보를 입력해주세요
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 4 }}>
              맞춤형 이벤트 추천을 위한 정보입니다
            </Typography>

            <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
              <TextField
                fullWidth
                label="상호명"
                placeholder="홍길동 고깃집"
                value={formData.businessName || ''}
                onChange={(e) => setFormData({ ...formData, businessName: e.target.value })}
                error={!!errors.businessName}
                helperText={errors.businessName}
                required
              />

              <Box sx={{ display: 'flex', gap: 1 }}>
                <TextField
                  fullWidth
                  label="사업자 번호"
                  placeholder="123-45-67890"
                  value={formData.businessNumber || ''}
                  onChange={(e) => {
                    const formatted = formatBusinessNumber(e.target.value);
                    setFormData({ ...formData, businessNumber: formatted });
                    setIsBusinessNumberVerified(false);
                  }}
                  error={!!errors.businessNumber}
                  helperText={
                    errors.businessNumber ||
                    (isBusinessNumberVerified
                      ? '✓ 인증 완료'
                      : '사업자 번호를 입력하고 인증해주세요')
                  }
                  required
                  sx={{
                    '& .MuiFormHelperText-root': {
                      color: isBusinessNumberVerified ? 'success.main' : undefined,
                    },
                  }}
                />
                <Button
                  variant="outlined"
                  size="large"
                  onClick={handleVerifyBusinessNumber}
                  disabled={isVerifyingBusinessNumber || isBusinessNumberVerified}
                  sx={{
                    minWidth: '90px',
                    py: 1.5,
                    fontSize: 14,
                    fontWeight: 600,
                  }}
                >
                  {isVerifyingBusinessNumber
                    ? '인증중'
                    : isBusinessNumberVerified
                      ? '완료'
                      : '인증'}
                </Button>
              </Box>

              <FormControl fullWidth required error={!!errors.businessType}>
                <InputLabel>업종</InputLabel>
                <Select
                  value={formData.businessType || ''}
                  onChange={(e) => setFormData({ ...formData, businessType: e.target.value })}
                  label="업종"
                >
                  <MenuItem value="">업종을 선택하세요</MenuItem>
                  <MenuItem value="restaurant">음식점</MenuItem>
                  <MenuItem value="cafe">카페/베이커리</MenuItem>
                  <MenuItem value="retail">소매/편의점</MenuItem>
                  <MenuItem value="beauty">미용/뷰티</MenuItem>
                  <MenuItem value="fitness">헬스/피트니스</MenuItem>
                  <MenuItem value="education">학원/교육</MenuItem>
                  <MenuItem value="service">서비스업</MenuItem>
                  <MenuItem value="other">기타</MenuItem>
                </Select>
                {errors.businessType && (
                  <Typography variant="caption" color="error" sx={{ mt: 0.5, ml: 2 }}>
                    {errors.businessType}
                  </Typography>
                )}
              </FormControl>

              <TextField
                fullWidth
                label="주소"
                placeholder="예: 서울특별시 강남구 테헤란로 123"
                value={formData.businessLocation || ''}
                onChange={(e) => setFormData({ ...formData, businessLocation: e.target.value })}
                helperText="사업장 주소를 입력해주세요"
              />

              <TextField
                fullWidth
                label="영업시간"
                placeholder="예: 평일 09:00-18:00, 주말 휴무"
                value={formData.businessHours || ''}
                onChange={(e) => setFormData({ ...formData, businessHours: e.target.value })}
                helperText="선택 사항입니다"
              />

              <Box sx={{ mt: 1 }}>
                <FormGroup>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={formData.agreeTerms === true && formData.agreePrivacy === true}
                        onChange={(e) => {
                          const checked = e.target.checked;
                          setFormData({
                            ...formData,
                            agreeTerms: checked,
                            agreePrivacy: checked,
                            agreeMarketing: checked,
                          });
                        }}
                      />
                    }
                    label={
                      <Typography variant="body2" sx={{ fontWeight: 600 }}>
                        전체 동의
                      </Typography>
                    }
                  />
                  <Box sx={{ ml: 3, mt: 1, display: 'flex', flexDirection: 'column', gap: 0.5 }}>
                    <FormControlLabel
                      control={
                        <Checkbox
                          checked={formData.agreeTerms || false}
                          onChange={(e) =>
                            setFormData({ ...formData, agreeTerms: e.target.checked })
                          }
                        />
                      }
                      label={
                        <Typography
                          variant="body2"
                          color={errors.agreeTerms ? 'error' : 'text.primary'}
                        >
                          [필수] 이용약관 동의
                        </Typography>
                      }
                    />
                    <FormControlLabel
                      control={
                        <Checkbox
                          checked={formData.agreePrivacy || false}
                          onChange={(e) =>
                            setFormData({ ...formData, agreePrivacy: e.target.checked })
                          }
                        />
                      }
                      label={
                        <Typography
                          variant="body2"
                          color={errors.agreePrivacy ? 'error' : 'text.primary'}
                        >
                          [필수] 개인정보 처리방침 동의
                        </Typography>
                      }
                    />
                    <FormControlLabel
                      control={
                        <Checkbox
                          checked={formData.agreeMarketing || false}
                          onChange={(e) =>
                            setFormData({ ...formData, agreeMarketing: e.target.checked })
                          }
                        />
                      }
                      label={<Typography variant="body2">[선택] 마케팅 정보 수신 동의</Typography>}
                    />
                  </Box>
                </FormGroup>
                {(errors.agreeTerms || errors.agreePrivacy) && (
                  <Typography
                    variant="caption"
                    color="error"
                    sx={{ mt: 1, display: 'block', ml: 2 }}
                  >
                    필수 약관에 동의해주세요
                  </Typography>
                )}
              </Box>

              <Box sx={{ display: 'flex', gap: 2, mt: 2 }}>
                <Button
                  variant="outlined"
                  size="large"
                  onClick={handleBack}
                  sx={{
                    flex: 1,
                    py: { xs: 1.5, sm: 1.75 },
                    fontSize: { xs: 15, sm: 16 },
                    fontWeight: 600,
                    borderWidth: 2,
                  }}
                >
                  이전
                </Button>
                <Button
                  variant="contained"
                  size="large"
                  onClick={handleNext}
                  sx={{
                    flex: 1,
                    py: { xs: 1.5, sm: 1.75 },
                    fontSize: { xs: 15, sm: 16 },
                    ...getGradientButtonStyle('success'),
                  }}
                >
                  가입완료
                </Button>
              </Box>
            </Box>
          </Box>
        )}
      </Paper>

      {/* 회원가입 완료 다이얼로그 */}
      <Dialog open={successDialogOpen} onClose={handleSuccessDialogClose} maxWidth="xs" fullWidth>
        <DialogContent sx={{ textAlign: 'center', py: 6, px: 4 }}>
          <CheckCircle sx={{ fontSize: 80, color: 'success.main', mb: 2 }} />
          <Typography variant="h5" sx={{ fontWeight: 700, mb: 1 }}>
            회원가입 완료!
          </Typography>
          <Typography variant="body1" color="text.secondary" sx={{ mb: 2 }}>
            <strong>{formData.name}</strong>님, 환영합니다!
          </Typography>
          <Typography variant="body2" color="text.secondary">
            이제 KT AI 이벤트 마케팅 서비스를<br />
            이용하실 수 있습니다
          </Typography>
        </DialogContent>
        <DialogActions sx={{ justifyContent: 'center', pb: 3 }}>
          <Button
            variant="contained"
            size="large"
            onClick={handleSuccessDialogClose}
            sx={{
              minWidth: 200,
              py: { xs: 1.5, sm: 1.75 },
              fontSize: { xs: 15, sm: 16 },
              ...getGradientButtonStyle('success'),
            }}
          >
            시작하기
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}

export default function RegisterPage() {
  return (
    <Suspense
      fallback={
        <Box
          sx={{
            minHeight: '100vh',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          <Typography>Loading...</Typography>
        </Box>
      }
    >
      <RegisterForm />
    </Suspense>
  );
}
