'use client';

import Button from '@/components/Button';
import { Icon } from '@iconify/react';
import Modal, { useModal } from '@/components/Modal';
import DateInput from '@/components/input/DateInput';
import { OptionType, useSelect } from '@/components/input/SelectInput';
import { useState, useEffect, useRef, useCallback } from 'react';
import useSWR from 'swr';
import { DashboardApi } from '@/services/api/dashboard';
import { useFormik } from 'formik';
import {
  ProjectFlockApi,
  ProjectFlockKandangApi,
} from '@/services/api/production';
import { LocationApi } from '@/services/api/master-data';
import { generateDashboardPDF } from '@/components/pages/dashboard/export/DashboardPDF';
import {
  DashboardFilterType,
  getDashboardFilterSchema,
} from '@/components/pages/dashboard/filter/DashboardProductionFilter.schema';
import DashboardLineChart from '@/components/pages/dashboard/chart/DashboardLineChart';
import DashboardLineChartSkeleton from '@/components/pages/dashboard/skeleton/DashboardLineChartSkeleton';
import DashboardExportCharts, {
  DashboardExportChartsRef,
} from '@/components/pages/dashboard/export/DashboardExportCharts';
import { RadioGroup, RadioGroupItem } from '@/components/input/RadioInput';
import { DashboardMeta } from '@/types/api/dashboard/dashboard';
import DashboardStats from '@/components/pages/dashboard/chart/DashboardStats';
import { isResponseSuccess } from '@/lib/api-helper';
import AlertErrorList from '@/components/helper/form/FormErrors';
import { useFormikErrorList } from '@/services/hooks/useFormikErrorList';
import ButtonFilter from '@/components/helper/ButtonFilter';
import Dropdown from '@/components/Dropdown';
import Menu from '@/components/menu/Menu';
import MenuItem from '@/components/menu/MenuItem';
import { useDashboardStore } from '@/stores/dashboard';
import SelectInputRadio from '@/components/input/SelectInputRadio';
import SelectInputCheckbox from '@/components/input/SelectInputCheckbox';
import { useUiStore } from '@/stores/ui/ui.store';
import { cn } from '@/lib/helper';
import DashboardExportStats, {
  DashboardExportStatsRef,
} from '@/components/pages/dashboard/export/DashboardExportStats';
import { ProjectFlock } from '@/types/api/production/project-flock';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';

// Helper function to normalize values to array
const normalizeToArray = (
  value: OptionType | OptionType[] | null | undefined
): number[] => {
  if (!value) return [];
  if (Array.isArray(value)) {
    return value.map((v) => Number(v.value));
  }
  return [Number(value.value)];
};

const DashboardProduction = () => {
  const filterModal = useModal();

  // ===== DASHBOARD STORE =====
  const { filterValues, setFilterValues, resetFilterValues } =
    useDashboardStore();

  // ===== UI STORE (for navbar actions) =====
  const setNavbarActions = useUiStore((state) => state.setNavbarActions);
  const clearNavbarActions = useUiStore((state) => state.clearNavbarActions);

  const [analysisMode, setAnalysisMode] = useState<'OVERVIEW' | 'COMPARISON'>(
    (filterValues.analysisMode as 'OVERVIEW' | 'COMPARISON') || 'OVERVIEW'
  );
  const [selectedLocationIds, setSelectedLocationIds] = useState<number[]>(
    normalizeToArray(filterValues.location)
  );
  const [exporting, setExporting] = useState(false);
  const allChartsRef = useRef<DashboardExportChartsRef>(null);
  const allStatsRef = useRef<DashboardExportStatsRef>(null);

  // ===== FETCH DATA =====
  const {
    data: dashboardProductionResponse,
    isLoading: isLoadingDashboardProductionData,
  } = useSWR(
    [
      'dashboard-production',
      filterValues.startDate ?? '',
      filterValues.endDate ?? '',
      filterValues.analysisMode ?? 'OVERVIEW',
      normalizeToArray(filterValues.location).toString(),
      normalizeToArray(filterValues.flock).toString(),
      normalizeToArray(filterValues.kandang).toString(),
      filterValues.comparisonType ?? '',
    ],
    () =>
      DashboardApi.getDashboardProductionFetcher({
        start_date: filterValues.startDate || '',
        end_date: filterValues.endDate || '',
        analysis_mode:
          (filterValues.analysisMode as 'OVERVIEW' | 'COMPARISON') ||
          'OVERVIEW',
        location_ids: normalizeToArray(filterValues.location),
        flock_ids: normalizeToArray(filterValues.flock),
        kandang_ids: normalizeToArray(filterValues.kandang),
        comparison_type: filterValues.comparisonType || '',
      })
  );

  const dashboardProductionData = isResponseSuccess(dashboardProductionResponse)
    ? dashboardProductionResponse.data
    : undefined;

  // ===== SELECT =====
  const {
    setInputValue: setInputValueFlock,
    options: flockOptions,
    isLoadingOptions: isLoadingFlockOptions,
    loadMore: loadMoreFlock,
  } = useSelect<ProjectFlock>(
    ProjectFlockApi.basePath,
    'id',
    'flock_name',
    'search',
    {
      location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
    }
  );

  const {
    setInputValue: setInputValueLocation,
    options: locationOptions,
    isLoadingOptions: isLoadingLocationOptions,
    loadMore: loadMoreLocation,
  } = useSelect(LocationApi.basePath, 'id', 'name');

  const comparisonTypeOptions = [
    { value: 'FARM', label: 'Farm' },
    { value: 'FLOCK', label: 'Flock' },
    { value: 'KANDANG', label: 'Kandang' },
  ];

  // ===== FORMIK =====
  const formik = useFormik({
    initialValues: {
      startDate: filterValues.startDate ?? '',
      endDate: filterValues.endDate ?? '',
      flock: filterValues.flock ?? ([] as OptionType[]),
      location: filterValues.location ?? ([] as OptionType[]),
      kandang: filterValues.kandang ?? ([] as OptionType[]),
      analysisMode: filterValues.analysisMode ?? analysisMode,
      comparisonType: filterValues.comparisonType ?? '',
      locationIds: filterValues.locationIds ?? [],
      flockIds: filterValues.flockIds ?? [],
      kandangIds: filterValues.kandangIds ?? [],
    } as DashboardFilterType,
    enableReinitialize: true,
    validationSchema: getDashboardFilterSchema(analysisMode),
    onSubmit: (values) => {
      setFilterValues(values);
      filterModal.closeModal();
    },
  });

  const { resetForm } = formik;

  const selectedLocationValues = normalizeToArray(formik.values.location);
  const selectedFlockValues = normalizeToArray(formik.values.flock);

  const {
    setInputValue: setInputValueKandang,
    options: kandangOptions,
    isLoadingOptions: isLoadingKandangOptions,
    loadMore: loadMoreKandang,
  } = useSelect<ProjectFlockKandang>(
    ProjectFlockKandangApi.basePath,
    'kandang_id',
    'kandang.name',
    'search',
    {
      location_id:
        selectedLocationValues.length > 0
          ? selectedLocationValues.toString()
          : '',
      project_flock_id:
        selectedFlockValues.length > 0 ? selectedFlockValues.toString() : '',
    }
  );

  const handleResetFilter = useCallback(() => {
    resetForm();
    resetFilterValues(); // Clear stored filter values
    setAnalysisMode('OVERVIEW');
    setSelectedLocationIds([]);
    filterModal.closeModal();
  }, [filterModal, resetForm, resetFilterValues]);

  // ===== Formik Error List =====
  const { formErrorList, close, handleFormSubmit } = useFormikErrorList(formik);

  // ===== Export PDF =====
  const handleExportPDF = useCallback(async () => {
    await generateDashboardPDF({
      filterValues: formik.values,
      allStatsRef,
      allChartsRef,
      setExporting,
    });
  }, [formik.values]);

  // ===== Register Navbar Actions =====
  const openFilterModalRef = useRef(filterModal.openModal);
  openFilterModalRef.current = filterModal.openModal;

  useEffect(() => {
    setNavbarActions(
      <div className='hidden sm:flex flex-row justify-end gap-3 '>
        <ButtonFilter
          values={{
            ...formik.values,
            analysisMode: undefined,
          }}
          variant='outline'
          onClick={() => openFilterModalRef.current()}
        />
        <Dropdown
          trigger={
            <Button
              variant='outline'
              color='none'
              className={cn(
                'rounded-lg font-semibold text-sm gap-1.5',
                'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft'
              )}
            >
              <Icon width={20} height={20} icon='heroicons:cloud-arrow-down' />
              Export
              <div className='w-6.5 h-5 flex items-center justify-center border-l border-base-content/10'>
                <Icon width={14} height={14} icon='heroicons:chevron-down' />
              </div>
            </Button>
          }
          className={{
            content: 'w-full mt-1 p-0',
          }}
        >
          <Menu
            className={`p-0 w-full shadow-button-soft border border-base-content/10 rounded-lg ${exporting ? 'hidden' : ''}`}
          >
            <MenuItem
              className='text-sm p-3'
              title='PDF'
              onClick={handleExportPDF}
            />
          </Menu>
        </Dropdown>
      </div>
    );
  }, [formik.values, exporting, setNavbarActions, handleExportPDF]);

  // Cleanup only on unmount
  useEffect(() => {
    return () => {
      clearNavbarActions();
    };
  }, [clearNavbarActions]);

  return (
    <>
      <section className='w-full p-3 space-y-3'>
        <div className='flex sm:hidden flex-row justify-end gap-3 '>
          <ButtonFilter
            values={{
              ...formik.values,
              analysisMode: undefined,
            }}
            variant='outline'
            onClick={() => openFilterModalRef.current()}
          />
          <Dropdown
            trigger={
              <Button
                variant='outline'
                color='none'
                className={cn(
                  'p-2 rounded-lg font-semibold text-sm gap-1.5',
                  'text-sm text-base-content/50 border border-base-content/10 shadow-button-soft'
                )}
              >
                <Icon
                  width={20}
                  height={20}
                  icon='heroicons:cloud-arrow-down'
                />
                Export
                <div className='w-6.5 h-5 flex items-center justify-center border-l border-base-content/10'>
                  <Icon width={14} height={14} icon='heroicons:chevron-down' />
                </div>
              </Button>
            }
            className={{
              content:
                'w-full mt-1 p-0 shadow-button-soft border border-base-content/10 rounded-lg',
            }}
          >
            <Menu
              className={`p-0 w-full shadow-button-soft border border-base-content/10 rounded-lg ${exporting ? 'hidden' : ''}`}
            >
              <MenuItem
                className='text-sm p-3'
                title='PDF'
                onClick={handleExportPDF}
              />
            </Menu>
          </Dropdown>
        </div>
        {/* Dashboard Stats */}
        <div>
          {isLoadingDashboardProductionData ? (
            <div className='w-full min-h-screen flex items-center justify-center'>
              <span className='loading loading-spinner loading-xl'></span>
            </div>
          ) : (
            <DashboardStats
              data={dashboardProductionData?.statistics_data ?? []}
            />
          )}
        </div>

        {/* Use DashboardLineChart component or skeleton */}
        <div>
          {isLoadingDashboardProductionData ? (
            <DashboardLineChartSkeleton />
          ) : dashboardProductionData &&
            dashboardProductionData.charts &&
            Object.keys(dashboardProductionData.charts).length > 0 ? (
            <DashboardLineChart
              analysisMode={
                isResponseSuccess(dashboardProductionResponse)
                  ? dashboardProductionResponse.meta
                    ? (
                        dashboardProductionResponse.meta as unknown as DashboardMeta
                      ).filters?.analysis_mode
                    : analysisMode
                  : analysisMode
              }
              data={dashboardProductionData}
              selectedKandang={
                analysisMode === 'OVERVIEW'
                  ? (formik.values.kandang as OptionType)
                  : undefined
              }
            />
          ) : (
            <DashboardLineChartSkeleton
              meta={
                isResponseSuccess(dashboardProductionResponse)
                  ? (dashboardProductionResponse.meta as unknown as DashboardMeta)
                  : undefined
              }
            />
          )}
        </div>

        {/* Hidden container for all charts (used for PDF export in OVERVIEW mode) */}
        {dashboardProductionData && (
          <>
            {/* Export Stats Charts */}
            <div
              style={{
                position: 'absolute',
                left: '-9999px',
                top: 0,
                width: '1200px', // Fixed width for consistent PDF rendering
              }}
            >
              <DashboardExportStats
                ref={allStatsRef}
                data={dashboardProductionData?.statistics_data ?? []}
              />
            </div>

            {/* Export ALL Charts */}
            <div
              style={{
                position: 'absolute',
                left: '-9999px',
                top: 0,
                width: '1200px', // Fixed width for consistent PDF rendering
              }}
            >
              <DashboardExportCharts
                ref={allChartsRef}
                data={dashboardProductionData}
                analysisMode={
                  isResponseSuccess(dashboardProductionResponse)
                    ? dashboardProductionResponse.meta
                      ? (
                          dashboardProductionResponse.meta as unknown as DashboardMeta
                        ).filters?.analysis_mode
                      : analysisMode
                    : analysisMode
                }
              />
            </div>
          </>
        )}
      </section>

      <Modal
        ref={filterModal.ref}
        className={{
          modal: 'p-0',
          modalBox: 'p-0 rounded-[0.875rem]',
        }}
      >
        <div className='flex flex-col'>
          {/* Modal Header */}
          <div className='flex items-center justify-between p-4 border-b border-base-content/10'>
            <div className='flex items-center gap-2 text-primary'>
              <Icon icon='heroicons:funnel' width={20} height={20} />
              <h3 className='font-medium text-sm'>Filter Data</h3>
            </div>
            <Button
              variant='link'
              onClick={() => filterModal.closeModal()}
              className='text-gray-500 hover:text-gray-700'
            >
              <Icon icon='heroicons:x-mark' width={20} height={20} />
            </Button>
          </div>

          <form
            className='flex flex-col'
            onSubmit={handleFormSubmit}
            onReset={handleResetFilter}
          >
            <div className='flex flex-col p-4 gap-1.5'>
              {/* Rentang Waktu */}
              <div>
                <label className='flex text-xs items-center gap-2 py-2 font-semibold'>
                  Tanggal
                </label>
                <div className='flex items-center gap-2'>
                  <DateInput
                    name='startDate'
                    placeholder='Tanggal Mulai'
                    value={formik.values.startDate}
                    errorMessage={formik.errors.startDate}
                    onChange={formik.handleChange}
                    isError={
                      Boolean(formik.errors.startDate) &&
                      Boolean(formik.touched.startDate)
                    }
                  />
                  <hr className='w-full max-w-3 h-px border-base-content/10'></hr>
                  <DateInput
                    name='endDate'
                    placeholder='Tanggal Akhir'
                    value={formik.values.endDate}
                    errorMessage={formik.errors.endDate}
                    onChange={formik.handleChange}
                    isError={
                      Boolean(formik.errors.endDate) &&
                      Boolean(formik.touched.endDate)
                    }
                  />
                </div>
              </div>

              {/* Analysis Mode */}
              <div>
                <label className='block py-2 text-xs font-semibold'>
                  Analysis Mode
                </label>
                <RadioGroup
                  name='analysisMode'
                  value={formik.values.analysisMode}
                  onChange={(e) => {
                    formik.handleChange(e);
                    setAnalysisMode(
                      e.target.value as 'OVERVIEW' | 'COMPARISON'
                    );
                    // Reset all dependent fields when analysis mode changes
                    formik.setFieldValue('location', []);
                    formik.setFieldValue('flock', []);
                    formik.setFieldValue('kandang', []);
                    formik.setFieldValue('comparisonType', '');
                    setSelectedLocationIds([]);
                  }}
                  color='primary'
                  className={{
                    wrapper:
                      'w-full flex flex-row items-center font-medium text-base-content/50',
                    radioWrapper: 'w-full grid grid-cols-2 gap-0 p-0',
                  }}
                >
                  <RadioGroupItem
                    color='primary'
                    value='OVERVIEW'
                    label='Performance Overview'
                    className='w-full p-3'
                  />
                  <RadioGroupItem
                    color='primary'
                    value='COMPARISON'
                    label='Performance Comparison'
                    className='w-full p-3'
                  />
                </RadioGroup>
              </div>

              {formik.values.analysisMode === 'COMPARISON' && (
                <SelectInputRadio
                  label='Compared By'
                  value={comparisonTypeOptions.find(
                    (option) => option.value === formik.values.comparisonType
                  )}
                  onChange={(selected) =>
                    formik.setFieldValue(
                      'comparisonType',
                      selected ? (selected as OptionType).value : ''
                    )
                  }
                  errorMessage={formik.errors.comparisonType as string}
                  options={comparisonTypeOptions}
                  isLoading={isLoadingLocationOptions}
                  isError={
                    Boolean(formik.errors.comparisonType) &&
                    Boolean(formik.touched.comparisonType)
                  }
                  className={{
                    select: 'rounded-lg text-sm border-base-content/10',
                  }}
                  isClearable={true}
                />
              )}

              {/* Location */}
              {comparisonTypeOptions.find(
                (option) => option.value === formik.values.comparisonType
              )?.value === 'FARM' ? (
                <SelectInputCheckbox
                  label='Farm'
                  value={
                    formik.values.location as
                      | { value: number; label: string }
                      | { value: number; label: string }[]
                      | null
                      | undefined
                  }
                  onInputChange={setInputValueLocation}
                  onMenuScrollToBottom={loadMoreLocation}
                  onChange={(selected) => {
                    formik.setFieldValue('location', selected);
                    // Update selectedLocationIds for kandang filter
                    setSelectedLocationIds(normalizeToArray(selected));
                    // Reset dependent fields when location changes
                    formik.setFieldValue('flock', []);
                    formik.setFieldValue('kandang', []);
                  }}
                  errorMessage={formik.errors.location as string}
                  options={locationOptions}
                  isLoading={isLoadingLocationOptions}
                  isError={
                    Boolean(formik.errors.location) &&
                    Boolean(formik.touched.location)
                  }
                  className={{
                    select: 'rounded-lg text-sm border-base-content/10',
                  }}
                  isClearable={true}
                />
              ) : (
                <SelectInputRadio
                  label='Farm'
                  value={
                    formik.values.location as
                      | { value: number; label: string }
                      | { value: number; label: string }[]
                      | null
                      | undefined
                  }
                  onInputChange={setInputValueLocation}
                  onMenuScrollToBottom={loadMoreLocation}
                  onChange={(selected) => {
                    formik.setFieldValue('location', selected);
                    // Update selectedLocationIds for kandang filter
                    setSelectedLocationIds(normalizeToArray(selected));
                    // Reset dependent fields when location changes
                    formik.setFieldValue('flock', []);
                    formik.setFieldValue('kandang', []);
                  }}
                  errorMessage={formik.errors.location as string}
                  options={locationOptions}
                  isLoading={isLoadingLocationOptions}
                  isError={
                    Boolean(formik.errors.location) &&
                    Boolean(formik.touched.location)
                  }
                  className={{
                    select: 'rounded-lg text-sm border-base-content/10',
                  }}
                  isClearable={true}
                />
              )}

              {/* Flock */}
              {!(
                formik.values.analysisMode === 'COMPARISON' &&
                !(
                  formik.values.comparisonType === 'FLOCK' ||
                  formik.values.comparisonType === 'KANDANG'
                )
              ) && (
                <>
                  {comparisonTypeOptions.find(
                    (option) => option.value === formik.values.comparisonType
                  )?.value === 'FLOCK' ? (
                    <SelectInputCheckbox
                      label='Flock'
                      value={
                        formik.values.flock as
                          | { value: number; label: string }
                          | { value: number; label: string }[]
                          | null
                          | undefined
                      }
                      onChange={(selected) =>
                        formik.setFieldValue('flock', selected)
                      }
                      errorMessage={formik.errors.flock as string}
                      onInputChange={setInputValueFlock}
                      onMenuScrollToBottom={loadMoreFlock}
                      options={flockOptions}
                      isLoading={isLoadingFlockOptions}
                      isError={
                        Boolean(formik.errors.flock) &&
                        Boolean(formik.touched.flock)
                      }
                      className={{
                        select: 'rounded-lg text-sm border-base-content/10',
                      }}
                      isClearable={true}
                    />
                  ) : (
                    <SelectInputRadio
                      label='Flock'
                      value={
                        formik.values.flock as
                          | { value: number; label: string }
                          | { value: number; label: string }[]
                          | null
                          | undefined
                      }
                      onChange={(selected) =>
                        formik.setFieldValue('flock', selected)
                      }
                      errorMessage={formik.errors.flock as string}
                      onInputChange={setInputValueFlock}
                      onMenuScrollToBottom={loadMoreFlock}
                      options={flockOptions}
                      isLoading={isLoadingFlockOptions}
                      isError={
                        Boolean(formik.errors.flock) &&
                        Boolean(formik.touched.flock)
                      }
                      className={{
                        select: 'rounded-lg text-sm border-base-content/10',
                      }}
                      isClearable={true}
                    />
                  )}
                </>
              )}

              {/* Kandang */}
              {!(
                formik.values.analysisMode === 'COMPARISON' &&
                !(formik.values.comparisonType === 'KANDANG')
              ) && (
                <>
                  {comparisonTypeOptions.find(
                    (option) => option.value === formik.values.comparisonType
                  )?.value === 'KANDANG' ? (
                    <SelectInputCheckbox
                      label='Kandang'
                      value={
                        formik.values.kandang as
                          | { value: number; label: string }
                          | { value: number; label: string }[]
                          | null
                          | undefined
                      }
                      onChange={(selected) =>
                        formik.setFieldValue('kandang', selected)
                      }
                      errorMessage={formik.errors.kandang as string}
                      onInputChange={setInputValueKandang}
                      onMenuScrollToBottom={loadMoreKandang}
                      options={kandangOptions}
                      isLoading={isLoadingKandangOptions}
                      isError={
                        Boolean(formik.errors.kandang) &&
                        Boolean(formik.touched.kandang)
                      }
                      className={{
                        select: 'rounded-lg text-sm border-base-content/10',
                      }}
                      isClearable={true}
                    />
                  ) : (
                    <SelectInputRadio
                      label='Kandang'
                      value={
                        formik.values.kandang as
                          | { value: number; label: string }
                          | { value: number; label: string }[]
                          | null
                          | undefined
                      }
                      onChange={(selected) =>
                        formik.setFieldValue('kandang', selected)
                      }
                      errorMessage={formik.errors.kandang as string}
                      onInputChange={setInputValueKandang}
                      onMenuScrollToBottom={loadMoreKandang}
                      options={kandangOptions}
                      isLoading={isLoadingKandangOptions}
                      isError={
                        Boolean(formik.errors.kandang) &&
                        Boolean(formik.touched.kandang)
                      }
                      className={{
                        select: 'rounded-lg text-sm border-base-content/10',
                      }}
                      isClearable={true}
                    />
                  )}
                </>
              )}

              {formErrorList.length > 0 && (
                <div className='w-full'>
                  <AlertErrorList
                    formErrorList={formErrorList}
                    onClose={close}
                  />
                </div>
              )}
            </div>

            {/* Action Buttons */}
            <div className='flex justify-between gap-4 p-4 border-t border-base-content/10 bg-gray-100'>
              <Button
                type='reset'
                variant='soft'
                className='rounded-lg p-3 bg-gray-100 border-gray-100 text-base-content/65 hover:bg-base-content/10'
              >
                Reset Filter
              </Button>
              <Button
                type='submit'
                className='min-w-40 text-sm p-3 text-white rounded-lg'
              >
                Apply Filter
              </Button>
            </div>
          </form>
        </div>
      </Modal>
    </>
  );
};

export default DashboardProduction;
