'use client';

import { useState } from 'react';
import { useParams } from 'next/navigation';
import {
  Box,
  Container,
  Card,
  CardContent,
  Typography,
  TextField,
  Button,
  Checkbox,
  FormControlLabel,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Grid,
  Divider,
  Alert,
  CircularProgress,
} from '@mui/material';
import { Celebration, CheckCircle, Error as ErrorIcon } from '@mui/icons-material';
import { participate } from '@/shared/api/participation.api';
import type { ParticipationRequest } from '@/shared/types/api.types';

// Mock 데이터 (이벤트 정보는 추후 Event API로 대체)
const mockEventData = {
  title: '신규고객 유치 이벤트',
  prize: '커피 쿠폰',
  startDate: '2025-11-01',
  endDate: '2025-11-15',
  announcementDate: '2025-11-20',
};

export default function EventParticipatePage() {
  const params = useParams();
  const eventId = params.eventId as string;

  // Form state
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [email, setEmail] = useState('');
  const [agreedToPrivacy, setAgreedToPrivacy] = useState(false);

  // Error state
  const [nameError, setNameError] = useState('');
  const [phoneError, setPhoneError] = useState('');
  const [apiError, setApiError] = useState('');

  // UI state
  const [privacyDialogOpen, setPrivacyDialogOpen] = useState(false);
  const [successDialogOpen, setSuccessDialogOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  // 전화번호 자동 포맷팅
  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 handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const formatted = formatPhoneNumber(e.target.value);
    setPhone(formatted);
    setPhoneError('');
    setApiError('');
  };

  // 유효성 검사
  const validateForm = () => {
    let isValid = true;

    // 이름 검증 (2-50자)
    if (name.length < 2 || name.length > 50) {
      setNameError('이름은 2자 이상 50자 이하이어야 합니다');
      isValid = false;
    } else {
      setNameError('');
    }

    // 전화번호 검증 (패턴: ^\d{3}-\d{3,4}-\d{4}$)
    const phonePattern = /^010-\d{4}-\d{4}$/;
    if (!phonePattern.test(phone)) {
      setPhoneError('올바른 전화번호 형식이 아닙니다 (010-0000-0000)');
      isValid = false;
    } else {
      setPhoneError('');
    }

    // 개인정보 동의 검증
    if (!agreedToPrivacy) {
      alert('개인정보 수집 및 이용에 동의해주세요');
      isValid = false;
    }

    return isValid;
  };

  // 제출 처리
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) {
      return;
    }

    setSubmitting(true);
    setApiError('');

    try {
      // API 요청 데이터 생성
      const requestData: ParticipationRequest = {
        name,
        phoneNumber: phone,
        email: email || undefined,
        agreePrivacy: agreedToPrivacy,
        channel: 'web', // 웹 참여
      };

      // API 호출
      const response = await participate(eventId, requestData);

      if (response.success) {
        // 성공 시 다이얼로그 표시
        setSuccessDialogOpen(true);
        // 폼 초기화
        setName('');
        setPhone('');
        setEmail('');
        setAgreedToPrivacy(false);
      } else {
        // API 응답은 성공했지만 success가 false인 경우
        setApiError(response.message || '참여 신청에 실패했습니다.');
      }
    } catch (error: any) {
      console.error('참여 신청 오류:', error);

      // 에러 메시지 처리
      if (error.response?.data?.message) {
        setApiError(error.response.data.message);
      } else if (error.message) {
        setApiError(error.message);
      } else {
        setApiError('참여 신청 중 오류가 발생했습니다. 다시 시도해주세요.');
      }
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: 'background.default', py: 4 }}>
      <Container maxWidth="sm">
        {/* Event Banner */}
        <Card
          sx={{
            mb: 3,
            borderRadius: 3,
            overflow: 'hidden',
          }}
        >
          {/* Event Image */}
          <Box
            sx={{
              position: 'relative',
              width: '100%',
              height: 200,
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Celebration sx={{ fontSize: 80, color: 'white', opacity: 0.9 }} />
          </Box>

          {/* Event Info */}
          <CardContent sx={{ textAlign: 'center', py: 3 }}>
            <Typography variant="h5" sx={{ fontWeight: 700, mb: 1 }}>
              {mockEventData.title}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              참여하고 경품에 당첨되세요!
            </Typography>
          </CardContent>
        </Card>

        {/* Event Info */}
        <Grid container spacing={2} sx={{ mb: 3 }}>
          <Grid item xs={6}>
            <Card sx={{ borderRadius: 2 }}>
              <CardContent>
                <Typography variant="caption" color="text.secondary">
                  경품
                </Typography>
                <Typography variant="body1" sx={{ fontWeight: 600, mt: 0.5 }}>
                  {mockEventData.prize}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
          <Grid item xs={6}>
            <Card sx={{ borderRadius: 2 }}>
              <CardContent>
                <Typography variant="caption" color="text.secondary">
                  이벤트 기간
                </Typography>
                <Typography variant="body1" sx={{ fontWeight: 600, mt: 0.5, fontSize: '0.9rem' }}>
                  {mockEventData.startDate} ~<br />
                  {mockEventData.endDate}
                </Typography>
              </CardContent>
            </Card>
          </Grid>
        </Grid>

        {/* API Error Alert */}
        {apiError && (
          <Alert severity="error" sx={{ mb: 3 }} icon={<ErrorIcon />} onClose={() => setApiError('')}>
            {apiError}
          </Alert>
        )}

        {/* Participation Form */}
        <Card sx={{ borderRadius: 3 }}>
          <CardContent sx={{ p: 3 }}>
            <Typography variant="h6" sx={{ fontWeight: 700, mb: 3 }}>
              참여하기
            </Typography>

            <form onSubmit={handleSubmit}>
              <TextField
                fullWidth
                label="이름"
                value={name}
                onChange={(e) => {
                  setName(e.target.value);
                  setNameError('');
                  setApiError('');
                }}
                error={!!nameError}
                helperText={nameError || '2자 이상 50자 이하로 입력해주세요'}
                sx={{ mb: 2 }}
                required
                disabled={submitting}
              />

              <TextField
                fullWidth
                label="전화번호"
                value={phone}
                onChange={handlePhoneChange}
                error={!!phoneError}
                helperText={phoneError || '010-0000-0000 형식으로 입력해주세요'}
                placeholder="010-0000-0000"
                sx={{ mb: 2 }}
                required
                disabled={submitting}
              />

              <TextField
                fullWidth
                label="이메일 (선택)"
                type="email"
                value={email}
                onChange={(e) => {
                  setEmail(e.target.value);
                  setApiError('');
                }}
                placeholder="example@email.com"
                sx={{ mb: 3 }}
                disabled={submitting}
              />

              <Divider sx={{ mb: 2 }} />

              <FormControlLabel
                control={
                  <Checkbox
                    checked={agreedToPrivacy}
                    onChange={(e) => setAgreedToPrivacy(e.target.checked)}
                    color="primary"
                    disabled={submitting}
                  />
                }
                label={
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                    <Typography variant="body2">개인정보 수집 및 이용 동의</Typography>
                    <Typography
                      variant="body2"
                      color="primary"
                      sx={{
                        cursor: 'pointer',
                        textDecoration: 'underline',
                        fontWeight: 600,
                      }}
                      onClick={(e) => {
                        e.preventDefault();
                        setPrivacyDialogOpen(true);
                      }}
                    >
                      (필수)
                    </Typography>
                  </Box>
                }
                sx={{ mb: 3 }}
              />

              <Button
                type="submit"
                fullWidth
                variant="contained"
                size="large"
                disabled={submitting}
                sx={{
                  py: 1.5,
                  borderRadius: 2,
                  fontWeight: 700,
                  fontSize: '1rem',
                }}
              >
                {submitting ? (
                  <>
                    <CircularProgress size={24} sx={{ mr: 1, color: 'white' }} />
                    참여 중...
                  </>
                ) : (
                  '참여하기'
                )}
              </Button>
            </form>
          </CardContent>
        </Card>

        {/* Participants Count Info */}
        <Box sx={{ textAlign: 'center', mt: 3 }}>
          <Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
            당첨자 발표: {mockEventData.announcementDate}
          </Typography>
        </Box>

        {/* Privacy Policy Dialog */}
        <Dialog
          open={privacyDialogOpen}
          onClose={() => setPrivacyDialogOpen(false)}
          maxWidth="sm"
          fullWidth
        >
          <DialogTitle>개인정보 수집 및 이용 동의</DialogTitle>
          <DialogContent dividers>
            <Typography variant="body2" sx={{ mb: 2 }}>
              <strong>1. 수집하는 개인정보 항목</strong>
              <br />- 이름, 전화번호, 이메일(선택)
            </Typography>
            <Typography variant="body2" sx={{ mb: 2 }}>
              <strong>2. 개인정보의 수집 및 이용목적</strong>
              <br />- 이벤트 참여 확인 및 당첨자 연락
              <br />- 중복 참여 방지
            </Typography>
            <Typography variant="body2" sx={{ mb: 2 }}>
              <strong>3. 개인정보의 보유 및 이용기간</strong>
              <br />- 이벤트 종료 후 3개월까지 보관 후 파기
            </Typography>
            <Typography variant="body2" color="error">
              ※ 귀하는 개인정보 수집 및 이용을 거부할 권리가 있으나, 거부 시 이벤트 참여가
              제한됩니다.
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setPrivacyDialogOpen(false)}>닫기</Button>
          </DialogActions>
        </Dialog>

        {/* Success Dialog */}
        <Dialog
          open={successDialogOpen}
          onClose={() => setSuccessDialogOpen(false)}
          maxWidth="xs"
          fullWidth
        >
          <DialogContent sx={{ textAlign: 'center', py: 4 }}>
            <CheckCircle sx={{ fontSize: 80, color: 'success.main', mb: 2 }} />
            <Typography variant="h6" sx={{ fontWeight: 700, mb: 1 }}>
              참여 완료!
            </Typography>
            <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
              <strong>{name}</strong>님의 참여가 완료되었습니다
            </Typography>
            <Box
              sx={{
                bgcolor: 'background.default',
                p: 2,
                borderRadius: 2,
                mb: 2,
              }}
            >
              <Typography variant="caption" color="text.secondary">
                당첨자 발표
              </Typography>
              <Typography variant="body1" sx={{ fontWeight: 600 }}>
                {mockEventData.announcementDate}
              </Typography>
            </Box>
            <Typography variant="caption" color="text.secondary">
              당첨 시 등록하신 전화번호로 연락드립니다
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button
              fullWidth
              variant="contained"
              onClick={() => setSuccessDialogOpen(false)}
            >
              확인
            </Button>
          </DialogActions>
        </Dialog>
      </Container>
    </Box>
  );
}
