import { zodResolver } from '@hookform/resolvers/zod';
import { LoadingButton } from '@mui/lab';
import Grid from '@mui/material/Grid';
import { useState, useEffect } 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 z from 'zod';
// import Identitas from '../components/rekamSsp/Identitas';
import Divider from '@mui/material/Divider';
import FormSkeleton from 'src/shared/skeletons/FormSkeleton';
import PphDipotong from '../components/rekamSsp/PphDipotong';
import useGetKodeObjekPajak from '../hooks/useGetKodeObjekPajakSsp';
import DokumenReferensi from '../components/rekamSsp/DokumenReferensi';
import Agreement from 'src/shared/components/agreement/Agreement';
import Stack from '@mui/material/Stack';
import PanduanSspRekam from '../components/rekamSsp/PanduanSspRekam';
import useSaveSsp from '../hooks/useSaveSsp';
import { enqueueSnackbar } from 'notistack';
import { useNavigate, useParams } from 'react-router';
import useUpload from '../hooks/useUpload';
import { useGetSspById } from '../hooks/useGetSsp';
import Identitas from '../components/rekamSsp/Identitas';
import ModalUploadSsp from '../components/dialog/ModalUploadSsp';

const bpuSspSchema = z
  .object({
    tglPemotongan: z.string().nonempty('Tanggal Pemotongan harus diisi'),
    thnPajak: z.string().nonempty('Tahun Pajak harus diisi'),
    msPajak: z.string().nonempty('Masa Pajak harus diisi'),
    kdObjPjk: z.string().nonempty('Kode Objek Pajak harus diisi'),
    fgFasilitas: z.string().nonempty('Fasilitas harus diisi'),
    noDokLainnya: z.string().optional(),
    dpp: z.string().nonempty('Jumlah Penghasilan Bruto harus diisi'),
    tarif: z.union([z.string().nonempty('Tarif harus diisi'), z.number()]),
    pphDipotong: z.string().nonempty('PPh Yang Dipotong/Dipungut harus diisi'),
    namaDok: z.string().nonempty('Nama Dokumen harus diisi'),
    nomorDok: z.string().nonempty('Nomor Dokumen harus diisi'),
    tglDok: z.string().nonempty('Tanggal Dokumen harus diisi'),
    idTku: z.string().nonempty('Cabang harus diisi'),

    pasalPph: z.string().optional(),
    statusPph: z.string().optional(),
    kap: z.union([z.string(), z.number()]).optional(),
    kjs: z.union([z.string(), z.number()]).optional(),
  })
  .superRefine((data, ctx) => {
    // Field dianggap DISABLED kalau fgFasilitas kosong ('') atau '9'
    const isDisabled = ['', '9'].includes(data.fgFasilitas);

    // Jika tidak disabled, berarti aktif → wajib isi
    if (!isDisabled && (!data.noDokLainnya || data.noDokLainnya.trim() === '')) {
      ctx.addIssue({
        path: ['noDokLainnya'],
        code: 'custom',
        message: 'No Dokumen Lainnya harus diisi',
      });
    }
  });

const SspRekamView = () => {
  const { id, type } = useParams<{ id?: string; type?: 'ubah' | 'pengganti' | 'new' }>();

  const [isOpenPanduan, setIsOpenPanduan] = useState<boolean>(false);
  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 isEdit = type === 'ubah';
  const isPengganti = type === 'pengganti';

  const { data: existingSsp, isLoading: isLoadingSsp } = useGetSspById(id!, {
    enabled: !!id && (isEdit || isPengganti),
  });

  const { data: kodeObjekPajak, isLoading: isLoadingKop } = useGetKodeObjekPajak();
  const navigate = useNavigate();

  type BpuSspFormData = z.infer<typeof bpuSspSchema>;

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

  const uploadNr = useUpload();

  const handleOpenPanduan = () => setIsOpenPanduan(!isOpenPanduan);

  const defaultValues: BpuSspFormData = {
    tglPemotongan: '',
    thnPajak: '',
    msPajak: '',
    kdObjPjk: '',
    fgFasilitas: '',
    noDokLainnya: '',
    dpp: '',
    tarif: '',
    pphDipotong: '',
    namaDok: '',
    nomorDok: '',
    tglDok: '',
    idTku: '',
  };

  const methods = useForm<BpuSspFormData>({
    mode: 'all',
    resolver: zodResolver(bpuSspSchema),
    defaultValues,
  });

  const { reset, handleSubmit } = methods;

  useEffect(() => {
    if (isEdit || isPengganti) {
      if (existingSsp && !isLoadingKop) {
        // 🧩 Normalisasi nilai numeric ke string sebelum reset
        const normalized = {
          ...existingSsp,
          // dpp:
          //   existingSsp.dpp !== null && existingSsp.dpp !== undefined
          //     ? String(existingSsp.dpp)
          //     : '',
          tarif:
            existingSsp.tarif !== null && existingSsp.tarif !== undefined
              ? String(existingSsp.tarif)
              : '',
          pphDipotong:
            existingSsp.pphDipotong !== null && existingSsp.pphDipotong !== undefined
              ? String(existingSsp.pphDipotong)
              : '',
          masaPajak:
            existingSsp.msPajak !== null && existingSsp.msPajak !== undefined
              ? String(existingSsp.msPajak)
              : '',
          namaDok: existingSsp.namaDok ?? '',
          nomorDok: existingSsp.nomorDok ?? '',
          tglDok: existingSsp.tglDok ?? '',
        };

        reset(normalized);
        setIsFormPrefilled(true);
        setFormInitialized(true);
      }
    } else {
      setIsFormPrefilled(false);
      setFormInitialized(true);
    }
  }, [existingSsp, isLoadingKop, isEdit, isPengganti, reset]);

  const buildPayload = (values: BpuSspFormData) => {
    if (isEdit) {
      return {
        ...values,
        id,
        isPengganti: false,
      };
    }

    if (isPengganti) {
      return {
        ...values,
        id,
        isPengganti: true,
        idBupot: existingSsp?.idBupot,
        noBupot: existingSsp?.noBupot,
        revNo: existingSsp?.revNo ?? 0,
      };
    }

    return {
      ...values,
      isPengganti: false,
    };
  };

  const onSubmit = async (values: BpuSspFormData) => {
    console.log('ini ke klik');
    try {
      const payload = buildPayload(values);

      await saveSsp.mutateAsync(payload);

      enqueueSnackbar(
        isEdit
          ? 'Data berhasil diperbarui'
          : isPengganti
            ? 'Data pengganti berhasil disimpan'
            : 'Data berhasil disimpan',
        { variant: 'success' }
      );

      navigate('/unifikasi/ssp');
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Gagal menyimpan data', { variant: 'error' });
      console.error('❌ saveSsp error:', error);
    }
  };

  const handleSaveAndUpload = async (values: BpuSspFormData) => {
    try {
      const payload = buildPayload(values);
      const res: any = await saveSsp.mutateAsync(payload);

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

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

      enqueueSnackbar('Data berhasil disimpan dan diupload', { variant: 'success' });
      navigate('/unifikasi/ssp');
    } catch (error: any) {
      enqueueSnackbar(error.message || 'Gagal save & upload data', { variant: 'error' });
      console.error('❌ Upload error:', error);
    }
  };

  if (isLoadingSsp || isLoadingKop || !formInitialized) {
    return (
      <DashboardContent>
        <CustomBreadcrumbs
          heading={
            isEdit
              ? 'Ubah Bupot Unifikasi di Setor Sendiri'
              : isPengganti
                ? 'Bupot Pengganti'
                : 'Tambah Bupot di Setor Sendiri'
          }
          links={[
            { name: 'Dashboard', href: paths.dashboard.root },
            { name: 'e-Bupot di Setor Sendiri', href: paths.unifikasi.ssp },
            { name: isEdit ? 'Ubah' : isPengganti ? 'Pengganti' : 'Tambah' },
          ]}
        />

        <HeadingRekam
          label={
            isEdit
              ? 'Ubah Data Bukti Pemotongan/Pemungutan PPh di Setor Sendiri'
              : isPengganti
                ? 'Rekam Bukti Pengganti PPh di Setor Sendiri'
                : 'Rekam Data Bukti Potong PPh di Setor Sendiri'
          }
        />
        <FormSkeleton numberOfRows={8} />
      </DashboardContent>
    );
  }

  return (
    <DashboardContent>
      <CustomBreadcrumbs
        heading={
          isEdit
            ? 'Ubah Bupot di Setor Sendiri'
            : isPengganti
              ? 'Bupot di Setor Sendiri Pengganti'
              : 'Tambah Bupot di Setor Sendiri'
        }
        links={[
          { name: 'Dashboard', href: paths.dashboard.root },
          { name: 'e-Bupot di Setor Sendiri', href: paths.unifikasi.ssp },
          { name: isEdit ? 'Ubah' : isPengganti ? 'Pengganti' : 'Tambah' },
        ]}
      />

      <HeadingRekam
        label={
          isEdit
            ? 'Ubah Data Bukti Pemotongan/Pemungutan PPh di Setor Sendiri'
            : isPengganti
              ? 'Rekam Bukti Pengganti PPh di Setor Sendiri'
              : 'Rekam Data Bukti Potong PPh di Setor Sendiri'
        }
      />

      <Grid container columnSpacing={2}>
        <Grid size={{ xs: isOpenPanduan ? 8 : 11 }}>
          <FormProvider {...methods}>
            <form onSubmit={handleSubmit(onSubmit)}>
              <Identitas isPengganti={isPengganti} existingSsp={existingSsp} />
              <PphDipotong
                kodeObjectPajak={kodeObjekPajak?.data ?? []}
                isFormPrefilled={isFormPrefilled}
              />
              <DokumenReferensi />
              <Divider />
              <Grid size={12}>
                <Agreement
                  isCheckedAgreement={isCheckedAgreement}
                  setIsCheckedAgreement={setIsCheckedAgreement}
                  text="Dengan ini saya menyatakan bahwa Bukti Pemotongan/Pemungutan Unifikasi telah saya isi dengan benar secara elektronik sesuai dengan"
                />
              </Grid>
              <Stack direction="row" gap={2} justifyContent="end" marginTop={2}>
                <LoadingButton
                  type="button"
                  loading={saveSsp.isPending}
                  disabled={!isCheckedAgreement}
                  variant="outlined"
                  sx={{ color: '#143B88' }}
                  onClick={() => {
                    console.log('🟢 Save as Draft clicked');
                    methods.handleSubmit(
                      async (values) => {
                        console.log('✅ Form valid, calling onSubmit...');
                        await onSubmit(values);
                      },
                      (errors) => {
                        console.error('❌ Validation errors:', errors);
                      }
                    )();
                  }}
                >
                  Save as Draft
                </LoadingButton>
                <LoadingButton
                  type="button"
                  disabled={!isCheckedAgreement}
                  //   onClick={() => methods.handleSubmit(handleSaveAndUpload)()}
                  onClick={() => setIsUploadModalOpen(true)}
                  loading={uploadNr.isPending}
                  variant="contained"
                  sx={{ background: '#143B88' }}
                >
                  Save and Upload
                </LoadingButton>
              </Stack>
            </form>
          </FormProvider>
        </Grid>
        <Grid size={{ xs: isOpenPanduan ? 4 : 1 }}>
          <PanduanSspRekam handleOpen={handleOpenPanduan} isOpen={isOpenPanduan} />
        </Grid>
      </Grid>

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

export default SspRekamView;
