'use client';

import * as Yup from 'yup';
import { useState, useMemo } from 'react';
import { useForm } from 'react-hook-form';
//import { yupResolver }  from '@hookform/resolvers/yup';

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 MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import Select from '@mui/material/Select';
import { Controller } from 'react-hook-form';
import FormHelperText from '@mui/material/FormHelperText';

import { paths } from '@/routes/paths';
import RouterLink from '@/routes/router-link';
import { useRouter, useSearchParams } from '@/hooks';

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

import { useAuthContext } from '@/hooks';
import { PATH_AFTER_LOGIN } from '@/config-global';

import Iconify from '@/shared/components/iconify';
import FormProvider, { RHFTextField, RHFSelect } from '@/shared/components/hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import axiosInstancee, { axiosInstance3 } from '@/utils/axios';
import axios from 'axios';

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

interface Role {
  value: string;
  label: string;
}

interface RoleFormControlProps {
  field: {
    value: string;
    onChange: (value: any) => void;
    onBlur: () => void;
    name: string;
  };
  error?: {
    message?: string;
  };
  roles: Role[];
}


const RoleFormControl: React.FC<RoleFormControlProps> = ({ field, error, roles }) => {
  const defaultRoleControl = useMemo(() => (
    <FormControl fullWidth error={!!error}>
      <InputLabel id="role-select-label">Role</InputLabel>
      <Select
        {...field}
        labelId="role-select-label"
        label="Role"
        data-testid="role-select-default"
      >
        <MenuItem value="USER">User</MenuItem>
      </Select>
      {error?.message && <FormHelperText>{error.message}</FormHelperText>}
    </FormControl>
  ), [field, error]);

  // Memoize the roles selection component
  const rolesSelectionControl = useMemo(() => (
    <FormControl fullWidth error={!!error}>
      <InputLabel id="role-select-label">Role</InputLabel>
      <Select
        {...field}
        labelId="role-select-label"
        label="Role"
        data-testid="role-select-options"
      >
        {roles.map((role) => (
          <MenuItem 
            key={role.value} 
            value={role.value}
            data-testid={`role-option-${role.value}`}
          >
            {role.label}
          </MenuItem>
        ))}
      </Select>
      {error?.message && <FormHelperText>{error.message}</FormHelperText>}
    </FormControl>
  ), [field, error, roles]);

  return roles.length > 0 ? rolesSelectionControl : defaultRoleControl;
};

export default function JwtRegisterView() {
  const { register } = useAuthContext();

  const router = useRouter();

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

  const searchParams = useSearchParams();

  const returnTo = searchParams.get('returnTo');

  const password = useBoolean();

  const availableRoles = [
    { value: 'DEVELOPER', label: 'Developer' },
    { value: 'DESIGNER', label: 'Designer' },
    { value: 'BUSINESS_INTELLIGENCE', label: 'Business Intelligence' },
    { value: 'PROJECT_MANAGER', label: 'Project Manager' },
    { value: 'USER', label: 'Regular User' },
  ];

  const RegisterSchema = Yup.object().shape({
    firstName: Yup.string().required('First name required'),
    lastName: Yup.string().required('Last name required'),
    email: Yup.string().required('Email is required').email('Email must be a valid email address'),
    role: Yup.string().required('Role is required'),
    password: Yup.string().required('Password is required'),
    confirmPassword: Yup.string()
      .required('Password confirmation is required')
      .oneOf([Yup.ref('password')], 'Passwords must match'),
  });

  const defaultValues = {
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    confirmPassword: '',
    role: 'USER',
  };

  const methods = useForm({
    resolver: yupResolver(RegisterSchema),
    defaultValues,
  });

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

  const onSubmit = handleSubmit(async (data) => {
    try {
      const response = await axiosInstancee.post('/api/user/auth/signup',
        {
          ...data,
          picture: 'default.jpg',
          state: 'ACTIVE',
          rewards: 0,
          totalPoints: 0
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );
      const result = await response.data;
      router.push(returnTo || PATH_AFTER_LOGIN);
    } catch (error: any) {
      console.error(error);
      reset();
      setErrorMsg(typeof error === 'string' ? error : error.message);
    }
  });



  const renderHead = (
    <Stack spacing={2} sx={{ mb: 5, position: 'relative' }}>

      <Stack direction="row" spacing={0.5}>
        <Typography variant="body2"> Already have an account? </Typography>

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

  const renderTerms = (
    <Typography
      component="div"
      sx={{
        mt: 2.5,
        textAlign: 'center',
        typography: 'caption',
        color: 'text.secondary',
      }}
    >

    </Typography>
  );

  const renderForm = (
    <Stack spacing={2.5}>
      <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
        <RHFTextField name="firstName" label="First name" />
        <RHFTextField name="lastName" label="Last name" />
      </Stack>

      <RHFTextField name="email" label="Email address" />

      {/* Role Selection Dropdown */}
      <Controller
        name="role"
        control={methods.control}
        render={({ field, fieldState: { error } }) => (
          <RoleFormControl 
            field={field}
            error={error}
            roles={availableRoles}
          />
        )}
      />

      <RHFTextField
        name="password"
        label="Password"
        type={password.value ? 'text' : 'password'}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton onClick={password.onToggle} edge="end">
                <Iconify icon={password.value ? 'solar:eye-bold' : 'solar:eye-closed-bold'} />
              </IconButton>
            </InputAdornment>
          ),
        }}
      />

      <RHFTextField
        name="confirmPassword"
        label="Confirm Password"
        type={password.value ? 'text' : 'password'}
        InputProps={{
          endAdornment: (
            <InputAdornment position="end">
              <IconButton onClick={password.onToggle} edge="end">
                <Iconify icon={password.value ? 'solar:eye-bold' : 'solar:eye-closed-bold'} />
              </IconButton>
            </InputAdornment>
          ),
        }}
      />

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

  return (
    <>
      {renderHead}

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

      <FormProvider methods={methods} onSubmit={onSubmit}>
        {renderForm}
      </FormProvider>

      {renderTerms}
    </>
  );
}
