'use client';

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

import Link from '@mui/material/Link';
import Alert from '@mui/material/Alert';
import Stack from '@mui/material/Stack';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
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 { confirmPasswordReset } from 'src/auth/context/jwt';

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

const ResetPasswordSchema = zod
  .object({
    newPassword: zod
      .string()
      .min(1, { message: 'Password is required!' })
      .min(6, { message: 'Password must be at least 6 characters!' }),
    newPasswordConfirm: zod.string().min(1, { message: 'Please confirm your password!' }),
  })
  .refine((data) => data.newPassword === data.newPasswordConfirm, {
    message: 'Passwords do not match!',
    path: ['newPasswordConfirm'],
  });

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

function ResetPasswordContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const token = searchParams.get('token');

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

  const newPassword = useBoolean();
  const newPasswordConfirm = useBoolean();

  const methods = useForm({
    resolver: zodResolver(ResetPasswordSchema),
    defaultValues: { newPassword: '', newPasswordConfirm: '' },
  });

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

  const onSubmit = handleSubmit(async (data) => {
    if (!token) {
      setErrorMsg('Reset link is missing. Please request a new password reset.');
      return;
    }
    try {
      await confirmPasswordReset({
        token,
        newPassword: data.newPassword,
        newPasswordConfirm: data.newPasswordConfirm,
      });
      setSuccessMsg('Password changed successfully. You can now sign in with your new password.');
      setErrorMsg('');
    } catch (error) {
      console.error(error);
      const msg = error?.response?.data?.message || error?.response?.data?.detail || 'Failed to reset password. The link may have expired — please request a new one.';
      setErrorMsg(msg);
    }
  });

  if (!token) {
    return (
      <>
        <Stack spacing={1.5} sx={{ mb: 5 }}>
          <Typography variant="h5">Reset password</Typography>
        </Stack>
        <Alert severity="error" sx={{ mb: 3 }}>
          Reset link is missing. Please follow the link from your email or request a new one.
        </Alert>
        <Link component={RouterLink} href={paths.auth.jwt.forgotPassword} variant="subtitle2">
          Request new reset link
        </Link>
      </>
    );
  }

  if (successMsg) {
    return (
      <>
        <Stack spacing={1.5} sx={{ mb: 5 }}>
          <Typography variant="h5">Reset password</Typography>
        </Stack>
        <Alert severity="success" sx={{ mb: 3 }}>
          {successMsg}
        </Alert>
        <Link component={RouterLink} href={paths.auth.jwt.signIn} variant="subtitle2">
          Sign in
        </Link>
      </>
    );
  }

  return (
    <>
      <Stack spacing={1.5} sx={{ mb: 5 }}>
        <Typography variant="h5">Set new password</Typography>
        <Typography variant="body2" sx={{ color: 'text.secondary' }}>
          Enter your new password below.
        </Typography>
      </Stack>

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

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

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

          <LoadingButton
            fullWidth
            color="inherit"
            size="large"
            type="submit"
            variant="contained"
            loading={isSubmitting}
            loadingIndicator="Saving..."
          >
            Save new password
          </LoadingButton>
        </Stack>
      </Form>

      <Link
        component={RouterLink}
        href={paths.auth.jwt.signIn}
        variant="body2"
        color="inherit"
        sx={{ display: 'block', mt: 3, textAlign: 'center' }}
      >
        Back to sign in
      </Link>
    </>
  );
}

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

export function JwtResetPasswordView() {
  return (
    <Suspense fallback={<Typography variant="body2">Loading...</Typography>}>
      <ResetPasswordContent />
    </Suspense>
  );
}
