'use client';

import type { FormEvent } from 'react';
import type { IRoleItem } from 'src/contexts/types/role';

import axios from 'axios';
import dayjs from 'dayjs';
import * as zod from 'zod';
import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useForm, Controller, FormProvider } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { isValidPhoneNumber } from 'react-phone-number-input';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faUser,
  faHome,
  faPhone,
  faIdBadge,
  faEnvelope,
  faBuilding,
  faArrowLeft,
  faCalendarAlt,
  faMapMarkerAlt,
} from '@fortawesome/free-solid-svg-icons';

import { ExpandMore } from '@mui/icons-material';
import { alpha, useTheme } from '@mui/material/styles';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import {
  Box,
  Grid,
  Chip,
  Alert,
  Paper,
  Button,
  Divider,
  Snackbar,
  Container,
  TextField,
  Accordion,
  Typography,
  InputAdornment,
  AccordionSummary,
  AccordionDetails,
} from '@mui/material';

import { GATEWAY_API_URL } from 'src/config-global';

import { toast } from 'src/shared/components/snackbar';
import { Field, schemaHelper } from 'src/shared/components/hook-form';

import { useAuthContext } from 'src/auth/hooks';
import { STORAGE_KEY } from 'src/auth/context/jwt';
import { useAuth } from 'src/auth/context/jwt/use-auth';

// Types
interface Address {
  id?: number;
  country?: string;
  complimentaryAddress?: string;
  city?: string;
  fullAddress?: string;
  zipCode?: string;
  createdAt?: string;
}

// Zod validation schema
const profileSchema = zod.object({
  firstName: zod.string().min(1, { message: 'Le prénom est requis.' }),
  lastName: zod.string().min(1, { message: 'Le nom est requis.' }),
  email: zod
    .string()
    .min(1, { message: 'Adresse e-mail requise.' })
    .email({ message: 'Adresse e-mail invalide.' }),
  phoneNumber: schemaHelper.phoneNumber({ isValidPhoneNumber }),
  birthDate: zod.string().min(1, { message: 'La date de naissance est requise.' }),
  primaryAddress: zod
    .object({
      country: zod.string().optional(),
      complimentaryAddress: zod.string().optional(),
      city: zod.string().optional(),
      fullAddress: zod.string().optional(),
      zipCode: zod.string().optional(),
    })
    .optional(),
  secondaryAddress: zod
    .object({
      country: zod.string().optional(),
      complimentaryAddress: zod.string().optional(),
      city: zod.string().optional(),
      fullAddress: zod.string().optional(),
      zipCode: zod.string().optional(),
    })
    .optional(),
});

type ProfileFormData = zod.infer<typeof profileSchema>;

export default function EditProfileView() {
  const router = useRouter();
  const PROFILE_PAGE = '/dashboard/profile/profile';

  const { user } = useAuth();
  const theme = useTheme();

  // State for editing
  const [isEditing, setIsEditing] = useState(false);

  // Address states
  const [primaryAddress, setPrimaryAddress] = useState<Address>({
    country: user?.primaryAddress?.country || '',
    complimentaryAddress: user?.primaryAddress?.complimentaryAddress || '',
    city: user?.primaryAddress?.city || '',
    fullAddress: user?.primaryAddress?.fullAddress || '',
    zipCode: user?.primaryAddress?.zipCode || '',
  });

  const [secondaryAddress, setSecondaryAddress] = useState<Address>({
    country: user?.secondaryAddress?.country || '',
    complimentaryAddress: user?.secondaryAddress?.complimentaryAddress || '',
    city: user?.secondaryAddress?.city || '',
    fullAddress: user?.secondaryAddress?.fullAddress || '',
    zipCode: user?.secondaryAddress?.zipCode || '',
  });

  // State for success message
  const [openSnackbar, setOpenSnackbar] = useState(false);
  const { checkUserSession } = useAuthContext();

  // Form setup with react-hook-form
  const methods = useForm<ProfileFormData>({
    resolver: zodResolver(profileSchema),
    defaultValues: {
      firstName: user?.firstName || '',
      lastName: user?.lastName || '',
      email: user?.email || '',
      phoneNumber: user?.phoneNumber || '',
      birthDate: user?.birthDate ? dayjs(user.birthDate).format('YYYY-MM-DD') : '',
      primaryAddress,
      secondaryAddress,
    },
    mode: 'onChange',
  });

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = methods;

  // Handle form submission
  const onSubmit = async (data: ProfileFormData) => {
    setIsEditing(true);

    try {
      const baseUserData = {
        firstName: data.firstName,
        lastName: data.lastName,
        email: data.email,
        phoneNumber: data.phoneNumber,
        birthDate: data.birthDate ? dayjs(data.birthDate).format('YYYY-MM-DD') : '',
        primaryAddress,
        secondaryAddress,
      };

      const token = sessionStorage.getItem(STORAGE_KEY);
      const response = await axios({
        method: 'put',
        url: `${GATEWAY_API_URL}/api/user-management/admins/current-user`,
        data: baseUserData,
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      await checkUserSession?.();

      toast.success('Informations mises à jour avec succès !');
    } catch (error: any) {
      const errorMessage = error?.response?.data?.message;
      console.log(errorMessage);

      if (errorMessage === 'Email already exists') {
        toast.error('Cet email est déjà utilisé.');
      } else if (errorMessage === 'Missing data') {
        toast.error('Données manquantes.');
      } else {
        console.error("Erreur lors de la mise à jour de l'utilisateur:", error);
        toast.error('Erreur lors de la mise à jour!');
      }
    } finally {
      setIsEditing(false);
    }
  };

  // Handle closing snackbar
  const handleCloseSnackbar = () => {
    setOpenSnackbar(false);
  };

  // Handle address field changes
  const handleAddressChange = (
    addressType: 'primary' | 'secondary',
    field: keyof Address,
    value: string
  ) => {
    if (addressType === 'primary') {
      setPrimaryAddress((prev) => ({ ...prev, [field]: value }));
      setValue('primaryAddress', { ...primaryAddress, [field]: value });
    } else {
      setSecondaryAddress((prev) => ({ ...prev, [field]: value }));
      setValue('secondaryAddress', { ...secondaryAddress, [field]: value });
    }
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <Container maxWidth="xl" sx={{ py: 6 }}>
        {/* Page Title */}
        <Typography variant="h3" component="h1" align="center" sx={{ mb: 4, fontWeight: 'bold' }}>
          Modifier les informations personnelles
        </Typography>

        <Grid container spacing={4}>
          {/* Navigation Menu (Sidebar) */}
          <Grid item xs={12} md={3}>
            <Paper sx={{ p: 3, height: '100%', boxShadow: 3 }}>
              <Button
                onClick={() => router.push(PROFILE_PAGE)}
                startIcon={<FontAwesomeIcon icon={faArrowLeft} />}
                fullWidth
                size="large"
                sx={{ mb: 2, textAlign: 'left', justifyContent: 'flex-start' }}
                color="primary"
                variant="text"
              >
                Retour à la gestion de profil
              </Button>
              <Divider sx={{ my: 2 }} />
            </Paper>
          </Grid>

          {/* Main Section */}
          <Grid item xs={12} md={9}>
            <Paper sx={{ p: 4, boxShadow: 3 }}>
              <Typography variant="h4" gutterBottom sx={{ fontWeight: 'bold', mb: 2 }}>
                Modifier vos informations personnelles
              </Typography>
              <Typography variant="body1" color="text.secondary" paragraph sx={{ mb: 3 }}>
                Mettez à jour vos coordonnées et informations personnelles.
              </Typography>

              <Alert severity="info" sx={{ mb: 4 }}>
                La modification de votre adresse e-mail nécessitera une vérification par email pour
                être validée.
              </Alert>

              {/* Form */}
              <FormProvider {...methods}>
                <Box component="form" noValidate sx={{ mt: 2 }} onSubmit={handleSubmit(onSubmit)}>
                  <Grid container spacing={3}>
                    {/* Personal Information Section */}
                    <Grid item xs={12}>
                      <Typography variant="h6" sx={{ mb: 2, fontWeight: 'bold' }}>
                        Informations personnelles
                      </Typography>
                    </Grid>

                    {/* First Name & Last Name */}
                    <Grid item xs={12} sm={6}>
                      <Field.Text
                        name="firstName"
                        label="Prénom"
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <FontAwesomeIcon icon={faUser} />
                            </InputAdornment>
                          ),
                        }}
                      />
                    </Grid>

                    <Grid item xs={12} sm={6}>
                      <Field.Text
                        name="lastName"
                        label="Nom"
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <FontAwesomeIcon icon={faUser} />
                            </InputAdornment>
                          ),
                        }}
                      />
                    </Grid>

                    {/* Birth Date */}
                    <Grid item xs={12} sm={6}>
                      <Controller
                        name="birthDate"
                        control={control}
                        render={({ field, fieldState }) => (
                          <DatePicker
                            label="Date de naissance"
                            value={field.value ? dayjs(field.value, 'YYYY-MM-DD') : null}
                            onChange={(newValue) => {
                              if (newValue) {
                                field.onChange(newValue.format('YYYY-MM-DD'));
                              } else {
                                field.onChange('');
                              }
                            }}
                            format="DD/MM/YYYY"
                            slotProps={{
                              textField: {
                                fullWidth: true,
                                error: Boolean(fieldState.error),
                                helperText: fieldState.error?.message,
                                InputProps: {
                                  startAdornment: (
                                    <InputAdornment position="start">
                                      <FontAwesomeIcon icon={faCalendarAlt} />
                                    </InputAdornment>
                                  ),
                                },
                              },
                            }}
                          />
                        )}
                      />
                    </Grid>

                    {/* Job Title */}
                    <Grid item xs={12}>
                      <Typography
                        variant="body2"
                        color="text.secondary"
                        sx={{ mb: 1, display: 'flex', alignItems: 'center', gap: 1 }}
                      >
                        <InputAdornment position="start">
                          <FontAwesomeIcon icon={faIdBadge} />
                        </InputAdornment>
                        Rôles:
                      </Typography>

                      <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                        {user?.roles?.map((role: IRoleItem, idx: number) => (
                          <Chip
                            key={idx}
                            label={role.name ?? 'Nom inconnu'}
                            sx={{
                              bgcolor: alpha(theme.palette.primary.main, 0.1),
                              color: 'primary.dark',
                              fontWeight: 600,
                              borderRadius: 1.5,
                              py: 0.5,
                              transition: 'all 0.2s',
                              '&:hover': {
                                bgcolor: alpha(theme.palette.primary.main, 0.2),
                                transform: 'translateY(-2px)',
                                boxShadow: `0 4px 8px 0 ${alpha(theme.palette.primary.main, 0.2)}`,
                              },
                            }}
                          />
                        ))}
                      </Box>

                      <Typography
                        variant="caption"
                        color="text.secondary"
                        sx={{ mt: 1, display: 'block' }}
                      >
                        Ce champ est défini par le Super Administrateur et ne peut pas être modifié.
                      </Typography>
                    </Grid>

                    {/* Contact Information Section */}
                    <Grid item xs={12}>
                      <Typography variant="h6" sx={{ mb: 2, mt: 3, fontWeight: 'bold' }}>
                        Informations de contact
                      </Typography>
                    </Grid>

                    {/* Primary Email */}
                    <Grid item xs={12}>
                      <Field.Text
                        name="email"
                        label="Adresse email principale"
                        type="email"
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <FontAwesomeIcon icon={faEnvelope} />
                            </InputAdornment>
                          ),
                        }}
                      />
                    </Grid>

                    {/* Phone Number */}
                    <Grid item xs={12}>
                      <Field.Phone name="phoneNumber" label="Numéro de téléphone" />
                    </Grid>

                    {/* Address Section */}
                    <Grid item xs={12}>
                      <Typography variant="h6" sx={{ mb: 2, mt: 3, fontWeight: 'bold' }}>
                        Adresses
                      </Typography>

                      {/* Primary Address */}
                      <Accordion sx={{ mb: 2 }}>
                        <AccordionSummary expandIcon={<ExpandMore />}>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <FontAwesomeIcon icon={faHome} />
                            <Typography variant="subtitle1" fontWeight="medium">
                              Adresse principale
                            </Typography>
                          </Box>
                        </AccordionSummary>
                        <AccordionDetails>
                          <Grid container spacing={2}>
                            <Grid item xs={12}>
                              <TextField
                                fullWidth
                                label="Adresse complète"
                                value={primaryAddress.fullAddress}
                                onChange={(e) =>
                                  handleAddressChange('primary', 'fullAddress', e.target.value)
                                }
                                InputProps={{
                                  startAdornment: (
                                    <InputAdornment position="start">
                                      <FontAwesomeIcon icon={faMapMarkerAlt} />
                                    </InputAdornment>
                                  ),
                                }}
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <TextField
                                fullWidth
                                label="Ville"
                                value={primaryAddress.city}
                                onChange={(e) =>
                                  handleAddressChange('primary', 'city', e.target.value)
                                }
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <TextField
                                fullWidth
                                label="Code postal"
                                value={primaryAddress.zipCode}
                                onChange={(e) =>
                                  handleAddressChange('primary', 'zipCode', e.target.value)
                                }
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <TextField
                                fullWidth
                                label="Pays"
                                value={primaryAddress.country}
                                onChange={(e) =>
                                  handleAddressChange('primary', 'country', e.target.value)
                                }
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <TextField
                                fullWidth
                                label="Complément d'adresse"
                                value={primaryAddress.complimentaryAddress}
                                onChange={(e) =>
                                  handleAddressChange(
                                    'primary',
                                    'complimentaryAddress',
                                    e.target.value
                                  )
                                }
                              />
                            </Grid>
                          </Grid>
                        </AccordionDetails>
                      </Accordion>

                      {/* Secondary Address */}
                      <Accordion>
                        <AccordionSummary expandIcon={<ExpandMore />}>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <FontAwesomeIcon icon={faBuilding} />
                            <Typography variant="subtitle1" fontWeight="medium">
                              Adresse secondaire
                            </Typography>
                          </Box>
                        </AccordionSummary>
                        <AccordionDetails>
                          <Grid container spacing={2}>
                            <Grid item xs={12}>
                              <TextField
                                fullWidth
                                label="Adresse complète"
                                value={secondaryAddress.fullAddress}
                                onChange={(e) =>
                                  handleAddressChange('secondary', 'fullAddress', e.target.value)
                                }
                                InputProps={{
                                  startAdornment: (
                                    <InputAdornment position="start">
                                      <FontAwesomeIcon icon={faMapMarkerAlt} />
                                    </InputAdornment>
                                  ),
                                }}
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <TextField
                                fullWidth
                                label="Ville"
                                value={secondaryAddress.city}
                                onChange={(e) =>
                                  handleAddressChange('secondary', 'city', e.target.value)
                                }
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <TextField
                                fullWidth
                                label="Code postal"
                                value={secondaryAddress.zipCode}
                                onChange={(e) =>
                                  handleAddressChange('secondary', 'zipCode', e.target.value)
                                }
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <TextField
                                fullWidth
                                label="Pays"
                                value={secondaryAddress.country}
                                onChange={(e) =>
                                  handleAddressChange('secondary', 'country', e.target.value)
                                }
                              />
                            </Grid>
                            <Grid item xs={12} sm={6}>
                              <TextField
                                fullWidth
                                label="Complément d'adresse"
                                value={secondaryAddress.complimentaryAddress}
                                onChange={(e) =>
                                  handleAddressChange(
                                    'secondary',
                                    'complimentaryAddress',
                                    e.target.value
                                  )
                                }
                              />
                            </Grid>
                          </Grid>
                        </AccordionDetails>
                      </Accordion>
                    </Grid>
                  </Grid>

                  {/* Action Buttons */}
                  <Box sx={{ mt: 4, display: 'flex', justifyContent: 'flex-end', gap: 2 }}>
                    <Button
                      variant="outlined"
                      size="large"
                      color="primary"
                      onClick={() => router.push(PROFILE_PAGE)}
                    >
                      Annuler
                    </Button>
                    <Button
                      variant="contained"
                      color="primary"
                      size="large"
                      type="submit"
                      disabled={isEditing}
                    >
                      {isEditing ? (
                        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                          <span style={{ display: 'inline-block' }}>Enregistrement...</span>
                          <span
                            className="loader"
                            style={{
                              width: 16,
                              height: 16,
                              border: '2px solid #fff',
                              borderTop: '2px solid transparent',
                              borderRadius: '50%',
                              animation: 'spin 0.8s linear infinite',
                            }}
                          />
                        </Box>
                      ) : (
                        'Enregistrer les modifications'
                      )}
                    </Button>
                  </Box>
                </Box>
              </FormProvider>
            </Paper>
          </Grid>
        </Grid>

        {/* Snackbar for Confirmation */}
        <Snackbar
          open={openSnackbar}
          autoHideDuration={3000}
          onClose={handleCloseSnackbar}
          message="Modifications enregistrées avec succès"
          anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        />

        {/* CSS for loader animation */}
        {/* eslint-disable-next-line react/no-unknown-property */}
        <style jsx global>{`
          @keyframes spin {
            0% {
              transform: rotate(0deg);
            }
            100% {
              transform: rotate(360deg);
            }
          }
        `}</style>
      </Container>
    </LocalizationProvider>
  );
}
