'use client';

import * as React from 'react';
import RouterLink from 'next/link';
import { useParams, useRouter } from 'next/navigation';
//
import { COL_QUIZ_MF_CATEGORIES } from '@/constants';
import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
//
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 Divider from '@mui/material/Divider';
import FormControl from '@mui/material/FormControl';
import FormHelperText from '@mui/material/FormHelperText';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import OutlinedInput from '@mui/material/OutlinedInput';
import Select from '@mui/material/Select';
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 { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { z as zod } from 'zod';

import { paths } from '@/paths';
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 FormLoading from '@/components/loading';

import ErrorDisplay from '../error';
import type { EditFormProps } from './type';

// TODO: review this
const schema = zod.object({
  cat_name: zod.string().min(1, 'name-is-required').max(255),
  // accept file object when user change image
  // accept http string when user not changing image
  cat_image: zod.union([zod.array(zod.any()), zod.string()]).optional(),

  // position
  pos: zod.number().min(1, 'position is required').max(99),

  // it should be a valid JSON
  init_answer: zod
    .string()
    .refine(
      (value) => {
        try {
          JSON.parse(value);
          return true;
        } catch (error) {
          return false;
        }
      },
      { message: 'init_answer must be a valid JSON' }
    )
    .optional(),
  visible: zod.string(),
  slug: zod.string().min(0, 'slug-is-required').max(255).optional(),
  remarks: zod.string().optional(),
  description: zod.string().optional(),
  // NOTE: for image handling
  avatar: zod.string().optional(),
});

type Values = zod.infer<typeof schema>;

const defaultValues = {
  cat_name: '',
  cat_image: undefined,
  pos: 1,
  init_answer: JSON.stringify({}),
  visible: 'hidden',
  slug: '',
  remarks: '',
  description: '',
} satisfies Values;

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

  const { cat_id: catId } = useParams<{ cat_id: string }>();
  //
  const [isUpdating, setIsUpdating] = React.useState<boolean>(false);
  const [showLoading, setShowLoading] = React.useState<boolean>(false);
  //
  const [showError, setShowError] = React.useState({ show: false, detail: '' });

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

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

      const tempUpdate: EditFormProps = {
        cat_name: values.cat_name,
        cat_image: values.avatar ? [await base64ToFile(values.avatar)] : null,
        pos: values.pos,
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        init_answer: JSON.parse(values.init_answer || '{}'),

        visible: values.visible,
        slug: values.slug || 'not-defined',
        remarks: values.remarks,
        description: values.description,
        //
        // TODO: remove below
        type: '',
      };

      try {
        const result = await pb.collection(COL_QUIZ_MF_CATEGORIES).update(catId, tempUpdate);
        logger.debug(result);
        toast.success(t('edit.success'));
        router.push(paths.dashboard.mf_categories.list);
      } catch (error) {
        logger.error(error);
        toast.error(t('update.failed'));
      } finally {
        setIsUpdating(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]
  );

  // TODO: need to align with save form
  // use trycatch
  const [textDescription, setTextDescription] = React.useState<string>('');
  const [textRemarks, setTextRemarks] = React.useState<string>('');

  // load existing data when user arrive
  const loadExistingData = React.useCallback(
    async (id: string) => {
      setShowLoading(true);

      try {
        const result = await pb.collection(COL_QUIZ_MF_CATEGORIES).getOne(id);

        reset({ ...defaultValues, ...result, init_answer: JSON.stringify(result.init_answer) });
        setTextDescription(result.description);
        setTextRemarks(result.remarks);

        if (result.cat_image !== '') {
          const fetchResult = await fetch(
            `http://127.0.0.1:8090/api/files/${result.collectionId}/${result.id}/${result.cat_image}`
          );

          const blob = await fetchResult.blob();
          const url = await fileToBase64(blob);

          setValue('avatar', url);
        } else {
          setValue('avatar', '');
        }
      } catch (error) {
        logger.error(error);
        toast(t('list.error'));

        setShowError({ show: true, detail: JSON.stringify(error, null, 2) });
      } finally {
        setShowLoading(false);
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [catId]
  );

  React.useEffect(() => {
    void loadExistingData(catId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [catId]);

  if (showLoading) return <FormLoading />;
  if (showError.show)
    return (
      <ErrorDisplay
        message={t('error.unable-to-process-request')}
        code="500"
        details={showError.detail}
      />
    );

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Card>
        <CardContent>
          <Stack
            divider={<Divider />}
            spacing={4}
          >
            <Stack spacing={3}>
              <Typography variant="h6">{t('edit.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('edit.avatar')}</Typography>
                      <Typography variant="caption">{t('edit.avatarRequirements')}</Typography>
                      <Button
                        color="secondary"
                        onClick={() => {
                          avatarInputRef.current?.click();
                        }}
                        variant="outlined"
                      >
                        {t('edit.avatar_select')}
                      </Button>
                      <input
                        hidden
                        onChange={handleAvatarChange}
                        ref={avatarInputRef}
                        type="file"
                      />
                    </Stack>
                  </Stack>
                </Grid>
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isUpdating}
                    control={control}
                    name="cat_name"
                    render={({ field }) => (
                      <FormControl
                        disabled={isUpdating}
                        error={Boolean(errors.cat_name)}
                        fullWidth
                      >
                        <InputLabel required>{t('edit.cat_name')}</InputLabel>
                        <OutlinedInput {...field} />
                        {errors.cat_name ? <FormHelperText>{errors.cat_name.message}</FormHelperText> : null}
                      </FormControl>
                    )}
                  />
                </Grid>
                {/*  */}
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isUpdating}
                    control={control}
                    name="pos"
                    render={({ field }) => (
                      <FormControl
                        error={Boolean(errors.pos)}
                        fullWidth
                      >
                        <InputLabel required>{t('edit.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={isUpdating}
                    control={control}
                    name="slug"
                    render={({ field }) => (
                      <FormControl
                        error={Boolean(errors.slug)}
                        fullWidth
                      >
                        <InputLabel required>{t('edit.slug')}</InputLabel>
                        <OutlinedInput {...field} />
                        {errors.slug ? <FormHelperText>{errors.slug.message}</FormHelperText> : null}
                      </FormControl>
                    )}
                  />
                </Grid>
                {/*  */}
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isUpdating}
                    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={isUpdating}
                    control={control}
                    name="init_answer"
                    render={({ field }) => (
                      <FormControl
                        error={Boolean(errors.init_answer)}
                        fullWidth
                      >
                        <InputLabel required>{t('edit.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('edit.detail-information')}</Typography>
              <Grid
                container
                spacing={3}
              >
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isUpdating}
                    control={control}
                    name="description"
                    render={({ field }) => {
                      return (
                        <Box>
                          <Typography
                            variant="subtitle1"
                            color="text-secondary"
                          >
                            {t('edit.description')}
                          </Typography>
                          <Box sx={{ mt: '8px', '& .tiptap-container': { height: '200px' } }}>
                            <TextEditor
                              {...field}
                              content={textDescription}
                              onUpdate={({ editor }) => {
                                field.onChange({ target: { value: editor.getHTML() } });
                              }}
                              placeholder={t('edit.description.default')}
                            />
                          </Box>
                        </Box>
                      );
                    }}
                  />
                </Grid>
                <Grid
                  md={6}
                  xs={12}
                >
                  <Controller
                    disabled={isUpdating}
                    control={control}
                    name="remarks"
                    render={({ field }) => (
                      <Box>
                        <Typography
                          variant="subtitle1"
                          color="text.secondary"
                        >
                          {t('edit.remarks')}
                        </Typography>
                        <Box sx={{ mt: '8px', '& .tiptap-container': { height: '200px' } }}>
                          <TextEditor
                            content={textRemarks}
                            onUpdate={({ editor }) => {
                              field.onChange({ target: { value: editor.getText() } });
                            }}
                            hideToolbar
                            placeholder={t('edit.remarks.default')}
                          />
                        </Box>
                      </Box>
                    )}
                  />
                </Grid>
              </Grid>
            </Stack>
            {/*  */}
          </Stack>
        </CardContent>
        <CardActions sx={{ justifyContent: 'flex-end' }}>
          <Button
            color="secondary"
            component={RouterLink}
            href={paths.dashboard.mf_categories.list}
          >
            {t('edit.cancelButton')}
          </Button>

          <LoadingButton
            disabled={isUpdating}
            loading={isUpdating}
            type="submit"
            variant="contained"
          >
            {t('edit.updateButton')}
          </LoadingButton>
        </CardActions>
      </Card>
    </form>
  );
}
