'use client';

import * as React from 'react';
import { useRouter } from 'next/navigation';
import {
  Alert,
  Autocomplete,
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  FormControl,
  FormControlLabel,
  FormHelperText,
  Grid,
  IconButton,
  InputLabel,
  MenuItem,
  Select,
  Stack,
  Switch,
  TextField,
  Typography,
} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import SaveIcon from '@mui/icons-material/Save';
import { zodResolver } from '@hookform/resolvers/zod';
import { Controller, useForm } from 'react-hook-form';
import { enqueueSnackbar } from 'notistack';
import { z as zod } from 'zod';

import { AppLoader } from '@/components/core/app-loader';
import { paths } from '@/paths';
import {
  getApiErrorMessage,
  getVolunteerById,
  updateVolunteerForm,
} from '@/services/volunteer.service';
import type { PreferedMethodOfContact, Volunteer, VolunteerStatus } from '@/types/volunteer';

const schema = zod.object({
  firstName: zod.string().trim().min(2, 'First name must be at least 2 characters'),
  lastName: zod.string().trim().min(2, 'Last name must be at least 2 characters'),
  emailAddress: zod.string().trim().email('Enter a valid email address'),
  phoneNumber: zod
    .string()
    .trim()
    .min(8, 'Phone number must be 8–20 characters')
    .max(20, 'Phone number must be 8–20 characters'),
  address: zod.string().trim().min(1, 'Address is required'),
  preferedMethodOfcontact: zod.enum(['phoneNumber', 'emailAddress']),
  goodAt: zod.string().trim().min(1, 'Skills / good at is required'),
  interest: zod.array(zod.string().trim().min(1)).min(1, 'Add at least one interest'),
  hearFrom: zod.string().trim().min(1, 'How they heard about us is required'),
  status: zod.enum(['pending', 'accepted', 'rejected', 'deleted']),
  isEmailSubscribed: zod.boolean(),
  isPhoneSubscribed: zod.boolean(),
});

type FormValues = zod.infer<typeof schema>;

const statusOptions: VolunteerStatus[] = ['pending', 'accepted', 'rejected', 'deleted'];
const contactOptions: { value: PreferedMethodOfContact; label: string }[] = [
  { value: 'emailAddress', label: 'Email' },
  { value: 'phoneNumber', label: 'Phone' },
];

const headerButtonSx = {
  bgcolor: 'rgba(11, 5, 4, 0.8)',
  color: '#FFDD31',
  borderRadius: 3,
  px: 3,
  py: 1.5,
  fontWeight: 600,
  border: '1px solid rgba(11, 5, 4, 0.9)',
  '&:hover': {
    bgcolor: 'rgba(11, 5, 4, 0.9)',
    transform: 'translateY(-2px)',
  },
  transition: 'all 0.3s ease',
  '&:disabled': {
    bgcolor: 'rgba(11, 5, 4, 0.35)',
    color: 'rgba(255, 221, 49, 0.5)',
  },
};

interface EditVolunteerFormProps {
  volunteerId: string;
}

export function EditVolunteerForm({ volunteerId }: EditVolunteerFormProps): React.JSX.Element {
  const router = useRouter();
  const [loading, setLoading] = React.useState(true);
  const [saving, setSaving] = React.useState(false);
  const [loadError, setLoadError] = React.useState<string | null>(null);
  const [volunteer, setVolunteer] = React.useState<Volunteer | null>(null);

  const {
    control,
    handleSubmit,
    reset,
    formState: { errors, isValid, isDirty },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    mode: 'onChange',
    defaultValues: {
      firstName: '',
      lastName: '',
      emailAddress: '',
      phoneNumber: '',
      address: '',
      preferedMethodOfcontact: 'emailAddress',
      goodAt: '',
      interest: [],
      hearFrom: '',
      status: 'pending',
      isEmailSubscribed: false,
      isPhoneSubscribed: false,
    },
  });

  React.useEffect(() => {
    let active = true;

    const load = async () => {
      try {
        setLoading(true);
        setLoadError(null);
        const data = await getVolunteerById(volunteerId);
        if (!active) return;

        setVolunteer(data);
        reset({
          firstName: data.formData.firstName,
          lastName: data.formData.lastName,
          emailAddress: data.formData.emailAddress,
          phoneNumber: data.formData.phoneNumber,
          address: data.formData.address,
          preferedMethodOfcontact: data.formData.preferedMethodOfcontact,
          goodAt: data.formData.goodAt,
          interest: data.formData.interest,
          hearFrom: data.formData.hearFrom,
          status: data.status,
          isEmailSubscribed: data.formData.isEmailSubscribed,
          isPhoneSubscribed: data.formData.isPhoneSubscribed,
        });
      } catch (error) {
        if (!active) return;
        const message = getApiErrorMessage(error, 'Failed to load volunteer form');
        setLoadError(message);
        enqueueSnackbar(message, { variant: 'error' });
      } finally {
        if (active) setLoading(false);
      }
    };

    void load();
    return () => {
      active = false;
    };
  }, [volunteerId, reset]);

  const onSubmit = handleSubmit(async (values) => {
    try {
      setSaving(true);
      const result = await updateVolunteerForm(volunteerId, {
        firstName: values.firstName,
        lastName: values.lastName,
        emailAddress: values.emailAddress,
        phoneNumber: values.phoneNumber,
        address: values.address,
        preferedMethodOfcontact: values.preferedMethodOfcontact,
        goodAt: values.goodAt,
        interest: values.interest,
        hearFrom: values.hearFrom,
        status: values.status,
        isEmailSubscribed: values.isEmailSubscribed,
        isPhoneSubscribed: values.isPhoneSubscribed,
      });

      enqueueSnackbar(result.message, { variant: 'success' });
      router.push(paths.dashboard.volunteerDetails(volunteerId));
      router.refresh();
    } catch (error) {
      enqueueSnackbar(getApiErrorMessage(error, 'Failed to update volunteer form'), {
        variant: 'error',
      });
    } finally {
      setSaving(false);
    }
  });

  if (loading) {
    return <AppLoader size="lg" viewport="content" label="Loading volunteer form..." />;
  }

  if (loadError || !volunteer) {
    return (
      <Box sx={{ py: 2 }}>
        <Alert severity="error" sx={{ mb: 2 }}>
          {loadError || 'Volunteer form not found'}
        </Alert>
        <Button
          variant="outlined"
          startIcon={<ArrowBackIcon />}
          onClick={() => router.push(paths.dashboard.volunteers)}
        >
          Back to Volunteers
        </Button>
      </Box>
    );
  }

  const imageUrl = volunteer.formData.volunteerImage?.fileUrl;

  return (
    <Box sx={{ bgcolor: 'background.default', minHeight: '100vh', py: 2 }}>
      <Stack
        direction={{ xs: 'column', sm: 'row' }}
        justifyContent="space-between"
        alignItems={{ xs: 'stretch', sm: 'center' }}
        spacing={2}
        sx={{
          mb: 4,
          p: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Stack direction="row" spacing={1.5} alignItems="center">
          <IconButton
            onClick={() => router.push(paths.dashboard.volunteerDetails(volunteerId))}
            sx={{ color: '#0B0504' }}
          >
            <ArrowBackIcon />
          </IconButton>
          <Box>
            <Typography variant="h4" fontWeight={700} gutterBottom>
              Edit Volunteer Form
            </Typography>
            <Typography variant="body1" sx={{ opacity: 0.9 }}>
              Update application details for {volunteer.name}
            </Typography>
          </Box>
        </Stack>
        <Stack direction="row" spacing={1.5}>
          <Button
            variant="outlined"
            onClick={() => router.push(paths.dashboard.volunteerDetails(volunteerId))}
            disabled={saving}
            sx={{
              borderColor: 'rgba(11, 5, 4, 0.8)',
              color: '#0B0504',
              borderRadius: 3,
              fontWeight: 600,
            }}
          >
            Cancel
          </Button>
          <Button
            variant="contained"
            startIcon={saving ? <AppLoader size="xs" inline color="#FFDD31" /> : <SaveIcon />}
            onClick={onSubmit}
            disabled={!isValid || !isDirty || saving}
            sx={headerButtonSx}
          >
            {saving ? 'Saving...' : 'Save Changes'}
          </Button>
        </Stack>
      </Stack>

      <Grid container spacing={3}>
        <Grid item xs={12} md={4}>
          <Card sx={{ borderRadius: 3 }}>
            <CardContent>
              <Typography variant="h6" fontWeight={600} gutterBottom>
                Profile image
              </Typography>
              <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
                Image is display-only and cannot be changed from this form.
              </Typography>
              <Box
                sx={{
                  width: '100%',
                  minHeight: 220,
                  borderRadius: 2,
                  bgcolor: 'action.hover',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  overflow: 'hidden',
                }}
              >
                {imageUrl ? (
                  <Box
                    component="img"
                    src={imageUrl}
                    alt={volunteer.name}
                    sx={{ width: '100%', height: 240, objectFit: 'cover' }}
                  />
                ) : (
                  <Typography color="text.secondary">No image uploaded</Typography>
                )}
              </Box>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={8}>
          <Card sx={{ borderRadius: 3 }}>
            <CardContent>
              <Stack component="form" spacing={3} onSubmit={onSubmit} noValidate>
                <Grid container spacing={2}>
                  <Grid item xs={12} sm={6}>
                    <Controller
                      name="firstName"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="First name"
                          fullWidth
                          required
                          error={Boolean(errors.firstName)}
                          helperText={errors.firstName?.message}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Controller
                      name="lastName"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="Last name"
                          fullWidth
                          required
                          error={Boolean(errors.lastName)}
                          helperText={errors.lastName?.message}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Controller
                      name="emailAddress"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="Email address"
                          type="email"
                          fullWidth
                          required
                          error={Boolean(errors.emailAddress)}
                          helperText={errors.emailAddress?.message}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Controller
                      name="phoneNumber"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="Phone number"
                          fullWidth
                          required
                          error={Boolean(errors.phoneNumber)}
                          helperText={errors.phoneNumber?.message}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="address"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="Address"
                          fullWidth
                          required
                          multiline
                          minRows={2}
                          error={Boolean(errors.address)}
                          helperText={errors.address?.message}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Controller
                      name="preferedMethodOfcontact"
                      control={control}
                      render={({ field }) => (
                        <FormControl fullWidth required error={Boolean(errors.preferedMethodOfcontact)}>
                          <InputLabel>Preferred contact</InputLabel>
                          <Select {...field} label="Preferred contact">
                            {contactOptions.map((option) => (
                              <MenuItem key={option.value} value={option.value}>
                                {option.label}
                              </MenuItem>
                            ))}
                          </Select>
                          {errors.preferedMethodOfcontact && (
                            <FormHelperText>{errors.preferedMethodOfcontact.message}</FormHelperText>
                          )}
                        </FormControl>
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Controller
                      name="status"
                      control={control}
                      render={({ field }) => (
                        <FormControl fullWidth required error={Boolean(errors.status)}>
                          <InputLabel>Status</InputLabel>
                          <Select {...field} label="Status">
                            {statusOptions.map((status) => (
                              <MenuItem key={status} value={status}>
                                {status.charAt(0).toUpperCase() + status.slice(1)}
                              </MenuItem>
                            ))}
                          </Select>
                          {errors.status && <FormHelperText>{errors.status.message}</FormHelperText>}
                        </FormControl>
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="goodAt"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="Good at / skills"
                          fullWidth
                          required
                          error={Boolean(errors.goodAt)}
                          helperText={errors.goodAt?.message}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="interest"
                      control={control}
                      render={({ field }) => (
                        <Autocomplete
                          multiple
                          freeSolo
                          options={[]}
                          value={field.value}
                          onChange={(_, value) => field.onChange(value)}
                          renderTags={(value, getTagProps) =>
                            value.map((option, index) => (
                              <Chip
                                {...getTagProps({ index })}
                                key={`${option}-${index}`}
                                label={option}
                                size="small"
                              />
                            ))
                          }
                          renderInput={(params) => (
                            <TextField
                              {...params}
                              label="Interests"
                              required
                              error={Boolean(errors.interest)}
                              helperText={
                                errors.interest?.message ||
                                'Press Enter after each interest'
                              }
                            />
                          )}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <Controller
                      name="hearFrom"
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          label="How did they hear about us?"
                          fullWidth
                          required
                          error={Boolean(errors.hearFrom)}
                          helperText={errors.hearFrom?.message}
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Controller
                      name="isEmailSubscribed"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={
                            <Switch
                              checked={field.value}
                              onChange={(event) => field.onChange(event.target.checked)}
                            />
                          }
                          label="Email subscribed"
                        />
                      )}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <Controller
                      name="isPhoneSubscribed"
                      control={control}
                      render={({ field }) => (
                        <FormControlLabel
                          control={
                            <Switch
                              checked={field.value}
                              onChange={(event) => field.onChange(event.target.checked)}
                            />
                          }
                          label="Phone subscribed"
                        />
                      )}
                    />
                  </Grid>
                </Grid>
              </Stack>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  );
}
