'use client';

import { z as zod } from 'zod';
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import Link from '@mui/material/Link';
import Alert from '@mui/material/Alert';
import Stack from '@mui/material/Stack';
import MenuItem from '@mui/material/MenuItem';
import Checkbox from '@mui/material/Checkbox';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import FormControlLabel from '@mui/material/FormControlLabel';
import LoadingButton from '@mui/lab/LoadingButton';
import InputAdornment from '@mui/material/InputAdornment';

import { paths } from 'src/routes/paths';
import { useRouter } from 'src/routes/hooks';
import { RouterLink } from 'src/routes/components';

import { useBoolean } from 'src/hooks/use-boolean';

import { Iconify } from 'src/components/iconify';
import { Form, Field } from 'src/components/hook-form';

import { signUp } from 'src/auth/context/jwt';
import { useAuthContext } from 'src/auth/hooks';

// ----------------------------------------------------------------------

export const SignUpSchema = zod
  .object({
    firstName: zod.string().min(1, { message: 'First name is required!' }),
    lastName: zod.string().min(1, { message: 'Last name is required!' }),
    email: zod
      .string()
      .min(1, { message: 'Email is required!' })
      .email({ message: 'Email must be a valid email address!' }),
    role: zod.enum(['mentor', 'client', 'parent'], { message: 'Role is required!' }),
    city: zod.string().min(1, { message: 'City is required!' }),
    password: zod
      .string()
      .min(1, { message: 'Password is required!' })
      .min(6, { message: 'Password must be at least 6 characters!' }),
    passwordConfirm: zod.string().min(1, { message: 'Please confirm your password!' }),
  })
  .refine((data) => data.password === data.passwordConfirm, {
    message: 'Passwords do not match!',
    path: ['passwordConfirm'],
  });

// ----------------------------------------------------------------------

export function JwtSignUpView() {
  const { checkUserSession } = useAuthContext();
  const router = useRouter();

  const password = useBoolean();
  const passwordConfirm = useBoolean();

  const [errorMsg, setErrorMsg] = useState('');
  const [successMsg, setSuccessMsg] = useState('');
  const [consent, setConsent] = useState(false);

  const defaultValues = {
    firstName: '',
    lastName: '',
    email: '',
    role: 'client',
    city: '',
    password: '',
    passwordConfirm: '',
  };

  const methods = useForm({
    resolver: zodResolver(SignUpSchema),
    defaultValues,
  });

  const {
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const onSubmit = handleSubmit(async (data) => {
    if (!consent) {
      setErrorMsg('Please agree to the Terms of Service and Privacy Policy.');
      return;
    }

    try {
      const result = await signUp({
        email: data.email,
        password: data.password,
        passwordConfirm: data.passwordConfirm,
        firstName: data.firstName,
        lastName: data.lastName,
        role: data.role,
        city: data.city,
      });

      if (result?.requiresVerification) {
        setSuccessMsg(
          `A confirmation email has been sent to ${data.email}. Please follow the link to verify your account.`
        );
        return;
      }

      await checkUserSession?.();
      router.refresh();
    } catch (error) {
      console.error(error);
      const msg = error?.response?.data?.message || error?.response?.data?.detail || (error instanceof Error ? error.message : 'Registration error. Please check your data.');
      setErrorMsg(msg);
    }
  });

  const renderHead = (
    <Stack spacing={1.5} sx={{ mb: 5 }}>
      <Typography variant="h5">Get started absolutely free</Typography>

      <Stack direction="row" spacing={0.5}>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          Already have an account?
        </Typography>

        <Link component={RouterLink} href={paths.auth.jwt.signIn} variant="subtitle2">
          Sign in
        </Link>
      </Stack>
    </Stack>
  );

  if (successMsg) {
    return (
      <>
        {renderHead}
        <Alert severity="success">{successMsg}</Alert>
        <Stack sx={{ mt: 3 }}>
          <Link component={RouterLink} href={paths.auth.jwt.signIn} variant="subtitle2">
            Back to sign in
          </Link>
        </Stack>
      </>
    );
  }

  const renderForm = (
    <Stack spacing={3}>
      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
        <Field.Text name="firstName" label="First name" InputLabelProps={{ shrink: true }} />
        <Field.Text name="lastName" label="Last name" InputLabelProps={{ shrink: true }} />
      </Stack>

      <Field.Text name="email" label="Email address" InputLabelProps={{ shrink: true }} />

      <Field.Select name="role" label="Role" InputLabelProps={{ shrink: true }}>
        <MenuItem value="client">Student</MenuItem>
        <MenuItem value="mentor">Mentor</MenuItem>
        <MenuItem value="parent">Parent</MenuItem>
      </Field.Select>

      <Field.Text name="city" label="City (for timezone)" InputLabelProps={{ shrink: true }} />

      <Field.Text
        name="password"
        label="Password"
        placeholder="6+ characters"
        type={password.value ? 'text' : 'password'}
        InputLabelProps={{ shrink: true }}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton onClick={password.onToggle} edge="end">
                <Iconify icon={password.value ? 'solar:eye-bold' : 'solar:eye-closed-bold'} />
              </IconButton>
            </InputAdornment>
          ),
        }}
      />

      <Field.Text
        name="passwordConfirm"
        label="Confirm password"
        placeholder="6+ characters"
        type={passwordConfirm.value ? 'text' : 'password'}
        InputLabelProps={{ shrink: true }}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton onClick={passwordConfirm.onToggle} edge="end">
                <Iconify icon={passwordConfirm.value ? 'solar:eye-bold' : 'solar:eye-closed-bold'} />
              </IconButton>
            </InputAdornment>
          ),
        }}
      />

      <FormControlLabel
        control={<Checkbox checked={consent} onChange={(e) => setConsent(e.target.checked)} />}
        label={
          <Typography variant="body2">
            I agree to the{' '}
            <Link underline="always" color="text.primary">
              Terms of service
            </Link>{' '}
            and{' '}
            <Link underline="always" color="text.primary">
              Privacy policy
            </Link>
          </Typography>
        }
      />

      <LoadingButton
        fullWidth
        color="inherit"
        size="large"
        type="submit"
        variant="contained"
        loading={isSubmitting}
        loadingIndicator="Creating account..."
      >
        Create account
      </LoadingButton>
    </Stack>
  );

  return (
    <>
      {renderHead}

      {!!errorMsg && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {errorMsg}
        </Alert>
      )}

      <Form methods={methods} onSubmit={onSubmit}>
        {renderForm}
      </Form>
    </>
  );
}
