'use client';

import * as React from 'react';
import RouterLink from 'next/link';
import { useRouter } from 'next/navigation';
import { COL_QUIZ_LP_QUESTIONS } from '@/constants';
import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import { Avatar, Divider, MenuItem, Select } from '@mui/material';
// import Avatar from '@mui/material/Avatar';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import FormControl from '@mui/material/FormControl';
import FormHelperText from '@mui/material/FormHelperText';
import InputLabel from '@mui/material/InputLabel';
import OutlinedInput from '@mui/material/OutlinedInput';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Unstable_Grid2';
import { Camera as CameraIcon } from '@phosphor-icons/react/dist/ssr/Camera';
// import axios from 'axios';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z as zod } from 'zod';

import { paths } from '@/paths';
import isDevelopment from '@/lib/check-is-development';
import { logger } from '@/lib/default-logger';
import { base64ToFile, fileToBase64 } from '@/lib/file-to-base64';
import { pb } from '@/lib/pb';
import { TextEditor } from '@/components/core/text-editor/text-editor';
import { toast } from '@/components/core/toaster';

import type { CreateFormProps } from './type';

const schema = zod.object({
  cat_name: zod.string().min(1, 'name-is-required').max(255),
  cat_image: zod.array(zod.any()).optional(),
  pos: zod.number().min(1, 'position is required').max(99),
  init_answer: zod.string().optional(),
  visible: zod.string(),
  slug: zod.string().min(1, 'slug-is-required').max(255),
  remarks: zod.string().optional(),
  description: zod.string().optional(),
  // NOTE: for image handling
  avatar: zod.string().optional(),
  // TODO: remove me
  type: zod.string().optional(),
  isActive: zod.boolean().optional(),
  order: zod.number().optional(),
});

type Values = zod.infer<typeof schema>;

export const defaultValues = {
  cat_name: '',
  cat_image: undefined,
  pos: 1,
  init_answer: '',
  visible: 'hidden',
  slug: '',
  remarks: '',
  description: '',
} satisfies Values;

export function LpQuestionCreateForm(): React.JSX.Element {
  const router = useRouter();
  const { t } = useTranslation(['lp_questions']);

  const [isCreating, setIsCreating] = React.useState<boolean>(false);

  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    watch,
  } = useForm<Values>({ defaultValues, resolver: zodResolver(schema) });

  const onSubmit = React.useCallback(
    async (values: Values): Promise<void> => {
      setIsCreating(true);

      const payload: CreateFormProps = {
        cat_name: values.cat_name,
        cat_image: values.avatar ? [await base64ToFile(values.avatar)] : null,
        pos: values.pos,
        init_answer: values.init_answer,
        visible: values.visible,
        slug: values.slug,
        remarks: values.remarks,
        description: values.description,
        //
        // TODO: remove me
        type: 'type tet',
        isActive: true,
        order: 1,
      };

      try {
        const result = await pb.collection(COL_QUIZ_LP_QUESTIONS).create(payload);

        logger.debug(result);
        toast.success(t('create.success'));
        router.push(paths.dashboard.lp_questions.list);
      } catch (error) {
        logger.error(error);
        toast.error(t('create.failed'));
      } finally {
        setIsCreating(false);
      }
    },
    // t is not necessary here
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [router]
  );

  const avatarInputRef = React.useRef<HTMLInputElement>(null);
  const avatar = watch('avatar');

  const handleAvatarChange = React.useCallback(
    async (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files?.[0];

      if (file) {
        const url = await fileToBase64(file);
        setValue('avatar', url);
      }
    },
    [setValue]
  );

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Card>
        <CardContent>
          <Stack
            divider={<Divider />}
            spacing={4}
          >
            <Stack spacing={3}>
              <Typography variant="h6">{t('create.basic-info')}</Typography>
              <Grid
                container
                spacing={3}
              >
                <Grid xs={12}>
                  <Stack
                    direction="row"
                    spacing={3}
                    sx={{ alignItems: 'center' }}
                  >
                    <Box
                      sx={{
                        border: '1px dashed var(--mui-palette-divider)',
                        borderRadius: '5%',
                        display: 'inline-flex',
                        p: '4px',
                      }}
                    >
                      <Avatar
                        variant="rounded"
                        src={avatar}
                        sx={{
                          '--Avatar-size': '100px',
                          '--Icon-fontSize': 'var(--icon-fontSize-lg)',
                          alignItems: 'center',
                          bgcolor: 'var(--mui-palette-background-level1)',
                          color: 'var(--mui-palette-text-primary)',
                          display: 'flex',
                          justifyContent: 'center',
                        }}
                      >
                        <CameraIcon fontSize="var(--Icon-fontSize)" />
                      </Avatar>
                    </Box>
                    <Stack
                      spacing={1}
                      sx={{ alignItems: 'flex-start' }}
                    >
                      <Typography variant="subtitle1">{t('create.avatar')}</Typography>
                      <Typography variant="caption">{t('create.avatarRequirements')}</Typography>
                      <Button
                        color="secondary"
                        onClick={() => {
                          avatarInputRef.current?.click();
                        }}
                        variant="outlined"
                      >
                        {t('create.avatar_select')}
                      </Button>
                      <input
                        hidden
                        onChange={handleAvatarChange}
                        ref={avatarInputRef}
                        type="file"
                      />
                    </Stack>
                  </Stack>
                </Grid>
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isCreating}
                    control={control}
                    name="cat_name"
                    render={({ field }) => (
                      <FormControl
                        disabled={isCreating}
                        error={Boolean(errors.cat_name)}
                        fullWidth
                      >
                        <InputLabel required>{t('create.cat_name')}</InputLabel>
                        <OutlinedInput {...field} />
                        {errors.cat_name ? <FormHelperText>{errors.cat_name.message}</FormHelperText> : null}
                      </FormControl>
                    )}
                  />
                </Grid>
                {/*  */}
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isCreating}
                    control={control}
                    name="pos"
                    render={({ field }) => (
                      <FormControl
                        error={Boolean(errors.pos)}
                        fullWidth
                      >
                        <InputLabel required>{t('create.pos')}</InputLabel>
                        <OutlinedInput
                          {...field}
                          onChange={(e) => {
                            field.onChange(parseInt(e.target.value));
                          }}
                          type="number"
                        />
                        {errors.pos ? <FormHelperText>{errors.pos.message}</FormHelperText> : null}
                      </FormControl>
                    )}
                  />
                </Grid>
                {/*  */}
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isCreating}
                    control={control}
                    name="slug"
                    render={({ field }) => (
                      <FormControl
                        error={Boolean(errors.slug)}
                        fullWidth
                      >
                        <InputLabel required>{t('create.slug')}</InputLabel>
                        <OutlinedInput {...field} />
                        {errors.slug ? <FormHelperText>{errors.slug.message}</FormHelperText> : null}
                      </FormControl>
                    )}
                  />
                </Grid>
                {/*  */}
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isCreating}
                    control={control}
                    name="visible"
                    render={({ field }) => (
                      <FormControl
                        error={Boolean(errors.visible)}
                        fullWidth
                      >
                        <InputLabel>{t('edit.visible')}</InputLabel>
                        <Select {...field}>
                          <MenuItem value="visible">{t('edit.visible')}</MenuItem>
                          <MenuItem value="hidden">{t('edit.hidden')}</MenuItem>
                        </Select>

                        {errors.visible ? <FormHelperText>{errors.visible.message}</FormHelperText> : null}
                      </FormControl>
                    )}
                  />
                </Grid>
                {/*  */}
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isCreating}
                    control={control}
                    name="init_answer"
                    render={({ field }) => (
                      <FormControl
                        error={Boolean(errors.init_answer)}
                        fullWidth
                      >
                        <InputLabel required>{t('create.init_answer')}</InputLabel>
                        <OutlinedInput {...field} />
                        {errors.init_answer ? <FormHelperText>{errors.init_answer.message}</FormHelperText> : null}
                      </FormControl>
                    )}
                  />
                </Grid>
              </Grid>
            </Stack>
            {/*  */}
            <Stack spacing={3}>
              <Typography variant="h6">{t('create.detail-information')}</Typography>
              <Grid
                container
                spacing={3}
              >
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isCreating}
                    control={control}
                    name="description"
                    render={({ field }) => {
                      return (
                        <Box>
                          <Typography
                            variant="subtitle1"
                            color="text-secondary"
                          >
                            {t('create.description')}
                          </Typography>
                          <Box sx={{ mt: '8px', '& .tiptap-container': { height: '400px' } }}>
                            <TextEditor
                              {...field}
                              content=""
                              onUpdate={({ editor }) => {
                                field.onChange({ target: { value: editor.getHTML() } });
                              }}
                              placeholder={t('create.description.default')}
                            />
                          </Box>
                        </Box>
                      );
                    }}
                  />
                </Grid>
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isCreating}
                    control={control}
                    name="remarks"
                    render={({ field }) => (
                      <Box>
                        <Typography
                          variant="subtitle1"
                          color="text.secondary"
                        >
                          {t('create.remarks')}
                        </Typography>
                        <Box sx={{ mt: '8px', '& .tiptap-container': { height: '400px' } }}>
                          <TextEditor
                            content=""
                            onUpdate={({ editor }) => {
                              field.onChange({ target: { value: editor.getText() } });
                            }}
                            hideToolbar
                            placeholder={t('create.remarks.default')}
                          />
                        </Box>
                      </Box>
                    )}
                  />
                </Grid>
              </Grid>
            </Stack>
            {/*  */}
          </Stack>
        </CardContent>
        <CardActions sx={{ justifyContent: 'flex-end' }}>
          <Button
            color="secondary"
            component={RouterLink}
            href={paths.dashboard.lp_questions.list}
          >
            {t('create.cancelButton')}
          </Button>

          <LoadingButton
            disabled={isCreating}
            loading={isCreating}
            type="submit"
            variant="contained"
          >
            {t('create.createButton')}
          </LoadingButton>
        </CardActions>
      </Card>
      <Box sx={{ display: isDevelopment ? 'block' : 'none' }}>
        <pre>{JSON.stringify({ errors }, null, 2)}</pre>
      </Box>
    </form>
  );
}
