'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import {
  Box,
  TextField,
  Button,
  Checkbox,
  FormControlLabel,
  Typography,
  Link,
  Divider,
  Paper,
  InputAdornment,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
} from '@mui/material';
import { Visibility, VisibilityOff, Email, Lock, ChatBubble, Info } from '@mui/icons-material';
import { useAuthContext } from '@/features/auth';
import { useUIStore } from '@/stores/uiStore';
import { getGradientButtonStyle, responsiveText } from '@/shared/lib/button-styles';

// 유효성 검사 스키마
const loginSchema = z.object({
  email: z.string().min(1, '이메일을 입력해주세요').email('올바른 이메일 형식이 아닙니다'),
  password: z.string().min(1, '비밀번호를 입력해주세요'),
  rememberMe: z.boolean().optional(),
});

type LoginFormData = z.infer<typeof loginSchema>;

export default function LoginPage() {
  const router = useRouter();
  const { login } = useAuthContext();
  const { showToast, setLoading } = useUIStore();
  const [showPassword, setShowPassword] = useState(false);
  const [openUnavailableModal, setOpenUnavailableModal] = useState(false);

  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    defaultValues: {
      email: '',
      password: '',
      rememberMe: false,
    },
  });

  const onSubmit = async (data: LoginFormData) => {
    console.log('🔐 로그인 시도:', { email: data.email });

    try {
      setLoading(true);

      // User API 호출
      const result = await login({
        email: data.email,
        password: data.password,
      });

      if (result.success) {
        console.log('✅ 로그인 성공:', result.user);
        showToast('로그인되었습니다', 'success');
        router.push('/');
      } else {
        console.error('❌ 로그인 실패:', result.error);
        showToast(
          result.error || '로그인에 실패했습니다. 이메일과 비밀번호를 확인해주세요.',
          'error'
        );
      }
    } catch (error) {
      console.error('💥 로그인 예외:', error);
      showToast('로그인 중 오류가 발생했습니다. 다시 시도해주세요.', 'error');
    } finally {
      setLoading(false);
    }
  };

  const handleUnavailableFeature = (e: React.MouseEvent) => {
    e.preventDefault();
    setOpenUnavailableModal(true);
  };

  const handleCloseModal = () => {
    setOpenUnavailableModal(false);
  };

  return (
    <Box
      sx={{
        minHeight: '100vh',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        px: { xs: 2, sm: 3 }, // 320px: 16px, 600px+: 24px
        py: { xs: 4, sm: 8 }, // 320px: 32px, 600px+: 64px
        background: 'linear-gradient(135deg, #FFF 0%, #F5F5F5 100%)',
      }}
    >
      <Paper
        elevation={0}
        sx={{
          width: '100%',
          maxWidth: 440,
          p: { xs: 2.5, sm: 4, md: 6 }, // 320px: 20px, 600px: 32px, 960px+: 48px
          borderRadius: 3,
          boxShadow: '0 8px 32px rgba(0,0,0,0.08)',
        }}
      >
        {/* 로고 및 타이틀 */}
        <Box sx={{ textAlign: 'center', mb: { xs: 4, sm: 6 } }}> {/* 320px: 32px, 600px+: 48px */}
          <Box
            sx={{
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: { xs: 56, sm: 64 }, // 320px: 56px, 600px+: 64px
              height: { xs: 56, sm: 64 },
              borderRadius: '50%',
              bgcolor: 'primary.main',
              mb: { xs: 2, sm: 3 }, // 320px: 16px, 600px+: 24px
            }}
          >
            <Typography sx={{ fontSize: { xs: 28, sm: 32 } }}>🎉</Typography> {/* 320px: 28px, 600px+: 32px */}
          </Box>
          <Typography
            variant="h4"
            sx={{
              ...responsiveText.h2,
              mb: 1,
              fontSize: { xs: '1.25rem', sm: '1.5rem' } // 320px: 20px, 600px+: 24px
            }}
          >
            KT 이벤트 파트너
          </Typography>
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{ fontSize: { xs: '0.813rem', sm: '0.875rem' } }} // 320px: 13px, 600px+: 14px
          >
            소상공인을 위한 마케팅 어시스턴트
          </Typography>
        </Box>

        {/* 로그인 폼 */}
        <form onSubmit={handleSubmit(onSubmit)}>
          <Box sx={{ mb: { xs: 2, sm: 3 } }}> {/* 320px: 16px, 600px+: 24px */}
            <Controller
              name="email"
              control={control}
              render={({ field }) => (
                <TextField
                  {...field}
                  fullWidth
                  label="이메일"
                  type="email"
                  placeholder="example@email.com"
                  error={!!errors.email}
                  helperText={errors.email?.message}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Email color="action" sx={{ fontSize: { xs: 20, sm: 24 } }} /> {/* 320px: 20px, 600px+: 24px */}
                      </InputAdornment>
                    ),
                  }}
                  sx={{
                    '& .MuiInputBase-input': {
                      fontSize: { xs: '0.875rem', sm: '1rem' } // 320px: 14px, 600px+: 16px
                    }
                  }}
                />
              )}
            />
          </Box>

          <Box sx={{ mb: { xs: 1.5, sm: 2 } }}> {/* 320px: 12px, 600px+: 16px */}
            <Controller
              name="password"
              control={control}
              render={({ field }) => (
                <TextField
                  {...field}
                  fullWidth
                  type={showPassword ? 'text' : 'password'}
                  label="비밀번호"
                  placeholder="8자 이상 입력하세요"
                  error={!!errors.password}
                  helperText={errors.password?.message}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <Lock color="action" sx={{ fontSize: { xs: 20, sm: 24 } }} />
                      </InputAdornment>
                    ),
                    endAdornment: (
                      <InputAdornment position="end">
                        <IconButton
                          onClick={() => setShowPassword(!showPassword)}
                          edge="end"
                          size="small"
                        >
                          {showPassword ? <VisibilityOff /> : <Visibility />}
                        </IconButton>
                      </InputAdornment>
                    ),
                  }}
                  sx={{
                    '& .MuiInputBase-input': {
                      fontSize: { xs: '0.875rem', sm: '1rem' }
                    }
                  }}
                />
              )}
            />
          </Box>

          <Box sx={{ mb: { xs: 2, sm: 3 } }}> {/* 320px: 16px, 600px+: 24px */}
            <Controller
              name="rememberMe"
              control={control}
              render={({ field }) => (
                <FormControlLabel
                  control={<Checkbox {...field} checked={field.value} size="small" />}
                  label={
                    <Typography
                      variant="body2"
                      color="text.secondary"
                      sx={{ fontSize: { xs: '0.813rem', sm: '0.875rem' } }} // 320px: 13px, 600px+: 14px
                    >
                      로그인 상태 유지
                    </Typography>
                  }
                />
              )}
            />
          </Box>

          <Button
            type="submit"
            fullWidth
            variant="contained"
            size="large"
            sx={{
              mb: 2,
              py: { xs: 1.25, sm: 1.5, md: 1.75 }, // 320px: 10px, 600px: 12px, 960px+: 14px
              fontSize: { xs: '0.938rem', sm: 15, md: 16 }, // 320px: 15px, 600px: 15px, 960px+: 16px
              ...getGradientButtonStyle('primary'),
            }}
          >
            로그인
          </Button>

          <Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              gap: { xs: 1.5, sm: 2 }, // 320px: 12px, 600px+: 16px
              mb: { xs: 3, sm: 4 }, // 320px: 24px, 600px+: 32px
              flexWrap: 'wrap'
            }}
          >
            <Link
              href="#"
              onClick={handleUnavailableFeature}
              variant="body2"
              color="text.secondary"
              underline="hover"
              sx={{
                cursor: 'pointer',
                fontSize: { xs: '0.813rem', sm: '0.875rem' } // 320px: 13px, 600px+: 14px
              }}
            >
              비밀번호 찾기
            </Link>
            <Typography
              variant="body2"
              color="text.secondary"
              sx={{ fontSize: { xs: '0.813rem', sm: '0.875rem' } }}
            >
              |
            </Typography>
            <Link
              href="#"
              onClick={handleUnavailableFeature}
              variant="body2"
              color="primary"
              underline="hover"
              sx={{
                cursor: 'pointer',
                fontWeight: 600,
                fontSize: { xs: '0.813rem', sm: '0.875rem' }
              }}
            >
              회원가입
            </Link>
          </Box>
        </form>

        {/* 소셜 로그인 */}
        <Divider sx={{ mb: { xs: 2, sm: 3 } }}> {/* 320px: 16px, 600px+: 24px */}
          <Typography
            variant="body2"
            color="text.secondary"
            sx={{ fontSize: { xs: '0.813rem', sm: '0.875rem' } }} // 320px: 13px, 600px+: 14px
          >
            또는
          </Typography>
        </Divider>

        <Box
          sx={{
            display: 'flex',
            flexDirection: 'column',
            gap: { xs: 1.5, sm: 2 }, // 320px: 12px, 600px+: 16px
            mb: { xs: 2, sm: 3 } // 320px: 16px, 600px+: 24px
          }}
        >
          <Button
            fullWidth
            variant="outlined"
            size="large"
            onClick={handleUnavailableFeature}
            sx={{
              py: { xs: 1.25, sm: 1.5 }, // 320px: 10px, 600px+: 12px
              fontSize: { xs: '0.875rem', sm: '0.938rem' }, // 320px: 14px, 600px+: 15px
              borderColor: '#FEE500',
              bgcolor: '#FEE500',
              color: '#000000',
              fontWeight: 600,
              '&:hover': {
                bgcolor: '#FDD835',
                borderColor: '#FDD835',
              },
            }}
            startIcon={<ChatBubble sx={{ fontSize: { xs: 20, sm: 24 } }} />}
          >
            카카오톡으로 시작하기
          </Button>

          <Button
            fullWidth
            variant="outlined"
            size="large"
            onClick={handleUnavailableFeature}
            sx={{
              py: { xs: 1.25, sm: 1.5 },
              fontSize: { xs: '0.875rem', sm: '0.938rem' },
              borderColor: '#03C75A',
              bgcolor: '#03C75A',
              color: '#FFFFFF',
              fontWeight: 600,
              '&:hover': {
                bgcolor: '#02B350',
                borderColor: '#02B350',
              },
            }}
            startIcon={
              <Box
                sx={{
                  width: { xs: 18, sm: 20 }, // 320px: 18px, 600px+: 20px
                  height: { xs: 18, sm: 20 },
                  borderRadius: '50%',
                  bgcolor: 'white',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontWeight: 700,
                  color: '#03C75A',
                  fontSize: { xs: 12, sm: 14 }, // 320px: 12px, 600px+: 14px
                }}
              >
                N
              </Box>
            }
          >
            네이버로 시작하기
          </Button>
        </Box>

        {/* 약관 동의 안내 */}
        <Typography
          variant="caption"
          color="text.secondary"
          sx={{
            textAlign: 'center',
            display: 'block',
            fontSize: { xs: '0.75rem', sm: '0.813rem' }, // 320px: 12px, 600px+: 13px
            lineHeight: 1.5
          }}
        >
          회원가입 시{' '}
          <Link
            href="#"
            onClick={handleUnavailableFeature}
            underline="hover"
            sx={{
              color: 'text.secondary',
              fontSize: 'inherit'
            }}
          >
            이용약관
          </Link>{' '}
          및{' '}
          <Link
            href="#"
            onClick={handleUnavailableFeature}
            underline="hover"
            sx={{
              color: 'text.secondary',
              fontSize: 'inherit'
            }}
          >
            개인정보처리방침
          </Link>
          에 동의하게 됩니다.
        </Typography>
      </Paper>

      {/* 지원하지 않는 기능 모달 */}
      <Dialog
        open={openUnavailableModal}
        onClose={handleCloseModal}
        maxWidth="xs"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 3,
            px: { xs: 1.5, sm: 2 }, // 320px: 12px, 600px+: 16px
            py: { xs: 0.5, sm: 1 }, // 320px: 4px, 600px+: 8px
            m: { xs: 2, sm: 3 }, // 320px: 16px, 600px+: 24px
          },
        }}
      >
        <DialogTitle
          sx={{
            display: 'flex',
            alignItems: 'center',
            gap: { xs: 1, sm: 1.5 }, // 320px: 8px, 600px+: 12px
            pb: { xs: 1.5, sm: 2 }, // 320px: 12px, 600px+: 16px
            px: { xs: 1, sm: 2 }, // 320px: 8px, 600px+: 16px
          }}
        >
          <Info color="info" sx={{ fontSize: { xs: 24, sm: 28 } }} /> {/* 320px: 24px, 600px+: 28px */}
          <Typography
            variant="h6"
            sx={{
              fontWeight: 600,
              fontSize: { xs: '1rem', sm: '1.125rem' } // 320px: 16px, 600px+: 18px
            }}
          >
            안내
          </Typography>
        </DialogTitle>
        <DialogContent sx={{ px: { xs: 2, sm: 3 } }}> {/* 320px: 16px, 600px+: 24px */}
          <Typography
            variant="body1"
            sx={{
              color: 'text.secondary',
              lineHeight: 1.7,
              fontSize: { xs: '0.875rem', sm: '1rem' } // 320px: 14px, 600px+: 16px
            }}
          >
            현재 지원하지 않는 기능입니다.
          </Typography>
        </DialogContent>
        <DialogActions sx={{ px: { xs: 2, sm: 3 }, pb: { xs: 2, sm: 3 } }}> {/* 320px: 16px, 600px+: 24px */}
          <Button
            onClick={handleCloseModal}
            variant="contained"
            fullWidth
            sx={{
              py: { xs: 1.25, sm: 1.5 }, // 320px: 10px, 600px+: 12px
              fontSize: { xs: '0.875rem', sm: '1rem' }, // 320px: 14px, 600px+: 16px
              ...getGradientButtonStyle('primary'),
            }}
          >
            확인
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
