import { LoadingButton } from '@mui/lab';
import Grid from '@mui/material/Grid';
import { useEffect, useMemo, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { CustomBreadcrumbs } from 'src/components/custom-breadcrumbs';
import { DashboardContent } from 'src/layouts/dashboard';
import { paths } from 'src/routes/paths';
import HeadingRekam from 'src/shared/components/HeadingRekam';
import FormSkeleton from 'src/shared/skeletons/FormSkeleton';
import Agreement from 'src/shared/components/agreement/Agreement';
import Stack from '@mui/material/Stack';
import { useNavigate, useParams } from 'react-router';

import { zodResolver } from '@hookform/resolvers/zod';
import type { Resolver } from 'react-hook-form';
import type { TReturPmForm } from '../types/types';
import { mapTrx017ToReturForm } from '../mappers/trx017ToReturForm';
import { mapTrx015ToReturForm } from '../mappers/trx015ToReturForm';
import { useGetFakturPMById, useGetReturPMById } from '../hooks/useGetReturFakturPM';
import { ReturPmSchema } from '../schemas/returPmSchema';
import InfoRetur from '../components/rekamReturPM/InfoRetur';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import DetailTransaksi from '../components/rekamReturPM/DetailTransaksi';
import TotalTransaksi from '../components/rekamReturPM/TotalTransaksi';
import TotalTransaksiRetur from '../components/rekamReturPM/TotalTransaksiRetur';
import ModalUploadReturPM from '../components/dialog/ModalUploadReturPM';
import usePostReturPM from '../hooks/usePostReturPM';
import { enqueueSnackbar } from 'notistack';
import useUploadReturPM from '../hooks/useUploadReturPM';
// import DetailTransaksi from '../../fakturPk/components/rekamFakturPK/DetailTransaksi';

const ReturRekamPmView = () => {
  const { id, type } = useParams<{ id?: string; type?: 'retur' | 'ubah' }>();

  const isRetur = type === 'retur';

  const fakturQuery = isRetur
    ? // eslint-disable-next-line react-hooks/rules-of-hooks
      useGetFakturPMById(id!, { enabled: !!id })
    : // eslint-disable-next-line react-hooks/rules-of-hooks
      useGetReturPMById(id!, { enabled: !!id });

  const { data, isLoading } = fakturQuery;

  const [isCheckedAgreement, setIsCheckedAgreement] = useState<boolean>(false);
  // const [isFormPrefilled, setIsFormPrefilled] = useState<boolean>(false);
  const [formInitialized, setFormInitialized] = useState<boolean>(false);
  const [isUploadModalOpen, setIsUploadModalOpen] = useState<boolean>(false);

  const postReturPM = usePostReturPM({
    onSuccess: () => enqueueSnackbar('Data berhasil disimpan', { variant: 'success' }),
  });

  const uploadReturPM = useUploadReturPM();

  const navigate = useNavigate();

  const formatMasaPajak = (value: any): string | null => {
    if (!value) return null;
    return dayjs(value).format('MM');
  };

  const formatTanggalRetur = (value: any): string | null => {
    if (!value) return null;
    return dayjs(value).format('DDMMYYYY');
  };

  const buildPayload = (values: TReturPmForm) => {
    const payload = {
      ...values,

      // 🔥 transform sesuai request BE
      masaPajakRetur: formatMasaPajak(values.masaPajakRetur),
      tanggalRetur: formatTanggalRetur(values.tanggalRetur),
    };

    if (type === 'ubah' && id) {
      return {
        ...payload,
        id,
      };
    }

    return payload;
  };

  const defaultValues: TReturPmForm = {
    masaPajakRetur: null,
    tahunPajakRetur: null,
    tanggalRetur: new Date(),
    nomorFakturDiretur: '',
    npwpPembeli: '',
    npwpPenjual: '',
    isCreditable: 1,

    nilaiReturDpp: 0,
    nilaiReturDppLain: 0,
    nilaiReturDiskon: 0,
    nilaiReturPpn: 0,
    nilaireturppnbm: 0,

    objekFaktur: [],
  };

  const methods = useForm<TReturPmForm>({
    defaultValues,
    // resolver: zodResolver(ReturPmSchema) as Resolver<TReturPmForm>,
    resolver: zodResolver(ReturPmSchema) as unknown as Resolver<TReturPmForm>,
    shouldUnregister: false,
  });

  const { handleSubmit } = methods;

  const handleSaveDraft = async (values: TReturPmForm) => {
    try {
      const payload = buildPayload(values);

      await postReturPM.mutateAsync(payload as any);

      enqueueSnackbar('Data berhasil disimpan sebagai draft', {
        variant: 'success',
      });
      navigate('/faktur/retur/pm');
    } catch (error: any) {
      enqueueSnackbar(error?.message || 'Gagal menyimpan draft', {
        variant: 'error',
      });
      console.error('❌ Save draft error:', error);
    }
  };

  const handleSaveAndUpload = async (values: TReturPmForm) => {
    try {
      const payload = buildPayload(values);

      const res: any = await postReturPM.mutateAsync(payload as any);

      const savedId = res?.id;
      if (!savedId) {
        throw new Error('ID dokumen tidak ditemukan dari hasil save');
      }

      await uploadReturPM.mutateAsync({ id: savedId });

      enqueueSnackbar('Data berhasil disimpan dan diupload', {
        variant: 'success',
      });
      navigate('/faktur/retur/pm');
    } catch (error: any) {
      enqueueSnackbar(error?.message || 'Gagal save & upload data', {
        variant: 'error',
      });
      console.error('❌ Save & upload error:', error);
    }
  };

  useEffect(() => {
    if (!data || formInitialized) return;

    const mapped: TReturPmForm =
      type === 'ubah' ? mapTrx017ToReturForm(data) : mapTrx015ToReturForm(data);

    methods.reset(mapped);
    setFormInitialized(true);
  }, [data, type, formInitialized, methods]);

  const onSubmit = () => {
    console.log('test');
  };

  const toDayjsOnly = (iso?: string): Dayjs | undefined => {
    if (!iso) return undefined;
    return dayjs(iso).startOf('day');
  };

  const minTanggalRetur = useMemo(() => toDayjsOnly(data?.tanggalfaktur), [data]);

  if (isLoading) {
    return (
      <DashboardContent>
        <CustomBreadcrumbs
          heading="Rekam Retur Pajak Masukan"
          links={[
            { name: 'Dashboard', href: paths.dashboard.root },
            { name: 'Retur Pajak Masukan ', href: paths.faktur.returPm },
            { name: 'Rekam' },
          ]}
        />

        <HeadingRekam label="Rekam Retur Pajak Masukan" />
        <FormSkeleton numberOfRows={8} />
      </DashboardContent>
    );
  }

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading="Rekam Retur Pajak Masukan"
        links={[
          { name: 'Dashboard', href: paths.dashboard.root },
          { name: 'Retur Pajak Masukan ', href: paths.faktur.returPm },
          { name: 'Rekam' },
        ]}
      />

      <HeadingRekam label="Rekam Retur Pajak Masukan" />

      <Grid container columnSpacing={2}>
        <Grid size={{ xs: 12 }}>
          <FormProvider {...methods}>
            <form onSubmit={handleSubmit(onSubmit)}>
              <InfoRetur minTanggalRetur={minTanggalRetur} />
              <DetailTransaksi rekamData={data} />
              <TotalTransaksi />
              <TotalTransaksiRetur data={data} type={type} />

              <Grid size={12}>
                <Agreement
                  isCheckedAgreement={isCheckedAgreement}
                  setIsCheckedAgreement={setIsCheckedAgreement}
                  text="Dengan ini saya menyatakan bahwa Faktur Pajak telah saya isi dengan benar, lengkap, dan jelas"
                />
              </Grid>
              <Stack direction="row" gap={2} justifyContent="end" marginTop={2}>
                <LoadingButton
                  type="button"
                  disabled={!isCheckedAgreement}
                  variant="outlined"
                  sx={{ color: '#143B88' }}
                  onClick={() => {
                    const values = methods.getValues();

                    handleSaveDraft({
                      ...values,
                      objekFaktur: values.objekFaktur,
                    } as any);

                    console.log('Save Draft jalan');
                  }}
                >
                  Save as Draft
                </LoadingButton>
                <LoadingButton
                  type="button"
                  disabled={!isCheckedAgreement}
                  onClick={() => setIsUploadModalOpen(true)}
                  variant="contained"
                  sx={{ background: '#143B88' }}
                >
                  Save and Upload
                </LoadingButton>
              </Stack>
            </form>
          </FormProvider>
        </Grid>
      </Grid>

      {isUploadModalOpen && (
        <ModalUploadReturPM
          isOpenDialogUpload={isUploadModalOpen}
          setIsOpenDialogUpload={setIsUploadModalOpen}
          onConfirmUpload={() => handleSaveAndUpload(methods.getValues())}
          singleUploadPayload={methods.getValues()}
        />
      )}
    </DashboardContent>
  );
};

export default ReturRekamPmView;
