import { Divider, Grid, Stack, Typography } from '@mui/material';
import { RHFNumeric } from 'src/components/hook-form/rhf-numeric';
import { FORM_FIELDS, FORM_SECTIONS, getFieldNameByIndex, isFieldReadOnly } from '../constant';
import { useFormContext } from 'react-hook-form';
import { Field } from 'src/components/hook-form';
import { memo, useEffect, useMemo } from 'react';
import { LoadingButton } from '@mui/lab';
import { CalculateRounded } from '@mui/icons-material';
import {
  getHitungBulananErrorMessage,
  useHitungTahunanA1 as hitungTahunanA1,
} from 'src/sections/bupot-21-26/hitung';
import dayjs from 'dayjs';

// ============================================
// REUSABLE COMPONENTS
// ============================================

export const FormFieldLabel = ({
  number,
  text,
  children = <></>,
}: {
  number: number;
  text: string;
  children?: React.ReactNode;
}) => (
  <Stack direction="row" spacing={2} justifyContent="space-between" alignItems="center">
    <Stack direction="row" spacing={2}>
      <Typography variant="subtitle1" fontWeight="bold" sx={{ minWidth: '40px' }}>
        {String(number).padStart(2, '0')}.
      </Typography>
      <Typography variant="subtitle1" fontWeight="bold">
        {text}
      </Typography>
    </Stack>
    {children}
  </Stack>
);

export const SectionTitle = ({ title }: { title: string }) => (
  <Divider sx={{ fontWeight: 'bold' }} textAlign="left">
    {title}
  </Divider>
);

const FormNumberInput = ({
  name,
  readOnly,
  size = 'small',
}: {
  name: string;
  readOnly: boolean;
  size?: string;
}) => (
  <RHFNumeric
    label=""
    name={name}
    size={size}
    allowNegativeValue={name === FORM_FIELDS.PPH_KURANG_LEBIH}
    negativeMask="both"
    readOnly={readOnly}
  />
);

const useRincianCalculations = () => {
  const { watch, setValue, clearErrors, trigger } = useFormContext();

  useEffect(() => {
    const subscription = watch((values, { name }) => {
      if (!name) return;

      let rincian8;

      switch (name) {
        // ✅ Rincian 1-7: Hitung total ke rincian8
        case 'rincian1':
        case 'rincian2':
        case 'rincian3':
        case 'rincian4':
        case 'rincian5':
        case 'rincian6':
        case 'rincian7':
          rincian8 =
            Number(values.rincian1 || 0) +
            Number(values.rincian2 || 0) +
            Number(values.rincian3 || 0) +
            Number(values.rincian4 || 0) +
            Number(values.rincian5 || 0) +
            Number(values.rincian6 || 0) +
            Number(values.rincian7 || 0);

          setValue('rincian8', rincian8);
          break;

        // ✅ Rincian 9-11: Hitung total ke rincian12
        case 'rincian9':
        case 'rincian10':
        case 'rincian11':
          setValue(
            'rincian12',
            Number(values.rincian9 || 0) +
              Number(values.rincian10 || 0) +
              Number(values.rincian11 || 0)
          );
          break;

        // ✅ Rincian 8 & 12: Hitung selisih ke rincian13
        case 'rincian8':
        case 'rincian12':
          setValue('rincian13', Number(values.rincian8 || 0) - Number(values.rincian12 || 0));
          break;

        // ✅ Rincian 18: Copy ke rincian19
        case 'rincian18':
          setValue('rincian19', Number(values.rincian18 || 0));
          break;

        // ✅ Rincian 19 & 20: Hitung selisih ke rincian21
        case 'rincian19':
        case 'rincian20':
          setValue('rincian21', Number(values.rincian19 || 0) - Number(values.rincian20 || 0));
          break;

        // ✅ Rincian 21 & 22: Hitung selisih ke rincian23
        case 'rincian21':
        case 'rincian22':
          setValue('rincian23', Number(values.rincian21 || 0) - Number(values.rincian22 || 0));
          break;

        // ✅ Rincian 14: Trigger validasi rincian20
        case 'rincian14':
          trigger('rincian20');
          break;

        default:
          break;
      }
    });

    return () => subscription.unsubscribe();
  }, [watch, setValue, clearErrors, trigger]);
};

// ============================================
// ✅ FIXED: Hook dipanggil di top-level component
// ============================================

const PerhitunganA1Builder = memo(
  ({
    listInputs = [],
    labelCols = 4,
    inputCols = 8,
    align = 'center',
  }: {
    listInputs: any;
    labelCols: any;
    inputCols: any;
    align?: any;
  }) => {
    if (listInputs.length === 0) {
      return null;
    }

    return (
      <Stack gap={2}>
        {listInputs.map((input: any) => {
          if (input.isSection) {
            return (
              <Grid container key={input.key} mt={3}>
                <Grid size={{ xs: 12 }}>{input.element}</Grid>
              </Grid>
            );
          }

          return (
            <Grid container alignItems={align} spacing={3} key={input.key}>
              <Grid size={{ xs: 12, md: labelCols }}>{input.label}</Grid>
              <Grid size={{ xs: 12, md: inputCols }}>{input.element}</Grid>
            </Grid>
          );
        })}
      </Stack>
    );
  }
);

PerhitunganA1Builder.displayName = 'PerhitunganA1Builder';

// ============================================
// ✅ MAIN COMPONENT: Hook dipanggil di sini
// ============================================

export default function PerhitunganA1Container() {
  // ✅ Hook dipanggil di top-level component
  const { watch, setValue, getValues } = useFormContext();
  const fgPerhitungan = watch('fgPerhitungan');
  const msPjkAwal = dayjs(watch('masaPajakAwal')).get('month') + 1;
  const isMetodePemotonganSeTahun = watch('metodePemotongan');


  useRincianCalculations();

  const { mutate, isPending } = hitungTahunanA1({
    onSuccess: (data: any) => {
      console.log('✅ Berhasil hitung Tahunan A1:', data);
      // TODO: Update form values dengan data dari response
      Object.keys(data).forEach((key) => {
        setValue(key, data[key]);
      });
    },
    onError: (error) => {
      console.error('❌ Error:', getHitungBulananErrorMessage(error));
    },
  });

  const handleHitung = () => {
    const currentValues = getValues(); // Ambil data terbaru
    console.log('📊 Data yang dikirim:', currentValues);
    mutate(currentValues as any);
  };

  const handleGrossUpChange = (_: any, checked: boolean) => {
    setValue('fgPerhitungan', checked ? '1' : '0');
    setValue('isGrossUp', checked);
  };

  const listInputs = useMemo(() => {
    const result: any[] = [];
    let globalIndex = 0;

    Object.values(FORM_SECTIONS).forEach((section) => {
      // Add section title
      result.push({
        key: `section-${section.title}`,
        isSection: true,
        element: <SectionTitle title={section.title} />,
      });

      // Add fields
      section.fields.forEach((label, localIndex) => {
        const fieldNumber = section.startNumber + localIndex;
        const fieldName = getFieldNameByIndex(globalIndex);
        const readOnly = isFieldReadOnly(fieldName, msPjkAwal, isMetodePemotonganSeTahun ,fgPerhitungan);

        // Special case: Tunjangan PPh dengan checkbox Gross Up
        if (fieldName === FORM_FIELDS.TUNJANGAN_PPH) {
          result.push({
            key: fieldName,
            label: (
              <FormFieldLabel number={fieldNumber} text={label}>
                <Field.Checkbox
                  name="isGrossUp"
                  label="Gross Up"
                  sx={{ padding: 0 }}
                  slotProps={{
                    checkbox: {
                      onChange: handleGrossUpChange,
                    },
                  }}
                />
              </FormFieldLabel>
            ),
            element: <FormNumberInput name={fieldName} readOnly={readOnly} />,
          });
        }
        // Special case: PPh dengan tombol Hitung
        else if (fieldName === FORM_FIELDS.PPH_ATAS_PKP) {
          result.push({
            key: fieldName,
            label: (
              <FormFieldLabel number={fieldNumber} text={label}>
                <LoadingButton
                  variant="contained"
                  size="medium"
                  color="primary"
                  sx={{ width: 120 }}
                  startIcon={<CalculateRounded />}
                  loading={isPending}
                  onClick={handleHitung} // ✅ Gunakan handler yang ambil data fresh
                >
                  Hitung
                </LoadingButton>
              </FormFieldLabel>
            ),
            element: <FormNumberInput name={fieldName} readOnly={readOnly} />,
          });
        }
        // Regular field
        else {
          result.push({
            key: fieldName,
            label: <FormFieldLabel number={fieldNumber} text={label} />,
            element: <FormNumberInput name={fieldName} readOnly={readOnly} />,
          });
        }

        globalIndex++;
      });
    });

    return result;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fgPerhitungan, isPending]);

  return <PerhitunganA1Builder listInputs={listInputs} labelCols={9} inputCols={3} />;
}
