'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 SelectInput, {
  OptionType,
  useSelect,
} from '@/components/input/SelectInput';
import { useState } from 'react';
import useSWR from 'swr';
import { DashboardApi } from '@/services/api/dashboard';
import { useFormik } from 'formik';
import { ProjectFlockApi } from '@/services/api/production';
import { KandangApi, LocationApi } from '@/services/api/master-data';

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 { RadioGroup, RadioGroupItem } from '@/components/input/RadioInput';
import {
  DashboardFilter,
  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';

// 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();
  const [analysisMode, setAnalysisMode] = useState<'OVERVIEW' | 'COMPARISON'>(
    'OVERVIEW'
  );
  const [endpointUrl, setEndpointUrl] = useState('/dashboards');
  const [selectedLocationIds, setSelectedLocationIds] = useState<number[]>([]);

  // ===== FETCH DATA =====
  const {
    data: dashboardProductionResponse,
    isLoading: isLoadingDashboardProductionData,
    mutate: refreshDashboardProductionData,
  } = useSWR(endpointUrl, () =>
    DashboardApi.getDashboardProductionFetcher(endpointUrl)
  );

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

  // ===== SELECT =====
  const { options: flockOptions, isLoadingOptions: isLoadingFlockOptions } =
    useSelect(ProjectFlockApi.basePath, 'id', 'flock_name', '', {
      limit: 'limit',
      location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
    });
  const {
    options: locationOptions,
    isLoadingOptions: isLoadingLocationOptions,
  } = useSelect(LocationApi.basePath, 'id', 'name', '', {
    limit: 'limit',
  });
  const { options: kandangOptions, isLoadingOptions: isLoadingKandangOptions } =
    useSelect(KandangApi.basePath, 'id', 'name', '', {
      limit: 'limit',
      location_id: selectedLocationIds ? selectedLocationIds.toString() : '',
    });
  const comparisonTypeOptions = [
    { value: 'FARM', label: 'Farm' },
    { value: 'FLOCK', label: 'Flock' },
    { value: 'KANDANG', label: 'Kandang' },
  ];

  // ===== FORMIK =====
  const formik = useFormik({
    initialValues: {
      startDate: '',
      endDate: '',
      flock: [] as OptionType[],
      location: [] as OptionType[],
      kandang: [] as OptionType[],
      analysisMode: analysisMode,
      comparisonType: '',
      lokasiIds: [],
      flockIds: [],
      kandangIds: [],
    } as DashboardFilterType,
    validationSchema: getDashboardFilterSchema(analysisMode),
    onSubmit: (values) => {
      console.log(values);

      handleApplyFilter({
        start_date: values.startDate || '',
        end_date: values.endDate || '',
        analysis_mode: values.analysisMode as 'OVERVIEW' | 'COMPARISON',
        location_ids: normalizeToArray(values.location),
        flock_ids: normalizeToArray(values.flock),
        kandang_ids: normalizeToArray(values.kandang),
        comparison_type: values.comparisonType,
      });
    },
  });

  const handleResetFilter = () => {
    formik.resetForm();
    setAnalysisMode('OVERVIEW');
    setEndpointUrl('/dashboards');
  };

  const handleApplyFilter = (values: DashboardFilter) => {
    console.log(values);

    // Build query params object, only include non-empty values
    const params: Record<string, string> = {};

    if (values.start_date) params.start_date = values.start_date;
    if (values.end_date) params.end_date = values.end_date;
    if (values.analysis_mode) params.analysis_mode = values.analysis_mode;
    if (values.location_ids.length > 0)
      params.location_ids = values.location_ids.toString();
    if (values.flock_ids.length > 0)
      params.flock_ids = values.flock_ids.toString();
    if (values.kandang_ids.length > 0)
      params.kandang_ids = values.kandang_ids.toString();
    if (values.comparison_type) params.comparison_type = values.comparison_type;

    setEndpointUrl(`/dashboards?${new URLSearchParams(params).toString()}`);
    console.log(endpointUrl);
    filterModal.closeModal();
    refreshDashboardProductionData();
    formik.resetForm();
  };

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

  if (isLoadingDashboardProductionData) {
    return (
      <div className='w-full min-h-screen flex items-center justify-center'>
        <span className='loading loading-spinner loading-xl'></span>
      </div>
    );
  }
  return (
    <>
      <section className='w-full p-4 space-y-6'>
        <div className='flex flex-col sm:flex-row items-center justify-between gap-4'>
          <div></div>
          <div className='flex flex-row justify-end gap-2'>
            <Button
              variant='outline'
              className={`min-w-28 rounded-lg ${
                isResponseSuccess(dashboardProductionResponse) &&
                (dashboardProductionResponse.meta as unknown as DashboardMeta)
                  .filters
                  ? 'bg-gradient-to-r from-blue-50 to-blue-100 border-blue-500 text-blue-600 hover:from-blue-100 hover:to-blue-200'
                  : ''
              }`}
              onClick={() => filterModal.openModal()}
            >
              <Icon
                icon='heroicons:funnel'
                width={20}
                height={20}
                className={
                  isResponseSuccess(dashboardProductionResponse) &&
                  (dashboardProductionResponse.meta as unknown as DashboardMeta)
                    .filters
                    ? 'text-blue-600'
                    : ''
                }
              />
              Filter
              {isResponseSuccess(dashboardProductionResponse) &&
                dashboardProductionResponse.meta &&
                (dashboardProductionResponse.meta as unknown as DashboardMeta)
                  .filters && (
                  <span className='w-6 h-6 text-white bg-red-500 rounded-lg flex items-center justify-center text-xs'>
                    {(() => {
                      const meta =
                        dashboardProductionResponse.meta as unknown as DashboardMeta;
                      if (!meta.filters) return 0;
                      const count =
                        (meta.filters.location_ids.length > 1
                          ? meta.filters.location_ids.length
                          : 0) +
                        (meta.filters.flock_ids.length > 1
                          ? meta.filters.flock_ids.length
                          : 0) +
                        (meta.filters.kandang_ids.length > 1
                          ? meta.filters.kandang_ids.length
                          : 0);
                      return meta.filters.analysis_mode === 'OVERVIEW'
                        ? 1
                        : count;
                    })()}
                  </span>
                )}
            </Button>
            <Button
              variant='outline'
              color='neutral'
              className='min-w-28 rounded-lg'
            >
              <Icon icon='heroicons:arrow-down-tray' width={20} height={20} />
              Export
              <Icon icon='heroicons:chevron-down' width={20} height={20} />
            </Button>
          </div>
        </div>

        {/* Dashboard Stats */}
        <DashboardStats data={dashboardProductionData?.statistics_data ?? []} />

        {/* Use DashboardLineChart component or skeleton */}
        {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}
          />
        ) : (
          <DashboardLineChartSkeleton
            meta={
              isResponseSuccess(dashboardProductionResponse)
                ? (dashboardProductionResponse.meta as unknown as DashboardMeta)
                : undefined
            }
          />
        )}
      </section>

      <Modal
        ref={filterModal.ref}
        className={{
          modal: 'p-0',
          modalBox: 'p-0 rounded-xl',
        }}
      >
        <div className='space-y-6'>
          {/* Modal Header */}
          <div className='flex items-center justify-between gap-2 py-3 border-b border-gray-300'>
            <div className='flex items-center gap-2 ms-4'>
              <Icon icon='heroicons:funnel' width={20} height={20} />
              <h3 className='font-semibold'>Filter Data</h3>
            </div>
            <Button
              variant='link'
              onClick={() => filterModal.closeModal()}
              className='text-gray-500 hover:text-gray-700 me-4 '
            >
              <Icon icon='heroicons:x-mark' width={20} height={20} />
            </Button>
          </div>

          <form
            className='space-y-4'
            onSubmit={handleFormSubmit}
            onReset={handleResetFilter}
          >
            {/* Rentang Waktu */}
            <div className='px-4'>
              <label className='flex items-center gap-2 mb-3'>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}
                  className={{
                    inputWrapper: 'rounded-lg',
                  }}
                  isError={
                    Boolean(formik.errors.startDate) &&
                    Boolean(formik.touched.startDate)
                  }
                />
                <span className='hidden md:block text-center'>—</span>
                <DateInput
                  name='endDate'
                  placeholder='Tanggal Akhir'
                  value={formik.values.endDate}
                  errorMessage={formik.errors.endDate}
                  onChange={formik.handleChange}
                  className={{
                    inputWrapper: 'rounded-lg',
                  }}
                  isError={
                    Boolean(formik.errors.endDate) &&
                    Boolean(formik.touched.endDate)
                  }
                />
              </div>
            </div>

            {/* Analysis Mode */}
            <div className='px-4'>
              <label className='block mb-3'>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 my-6 font-semibold text-neutral-500',
                }}
              >
                <RadioGroupItem
                  color='primary'
                  value='OVERVIEW'
                  label='Performance Overview'
                />
                <RadioGroupItem
                  color='primary'
                  value='COMPARISON'
                  label='Performance Comparison'
                />
              </RadioGroup>
            </div>

            {formik.values.analysisMode === 'COMPARISON' && (
              <div className='px-4'>
                <SelectInput
                  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)
                  }
                />
              </div>
            )}

            {/* Location */}
            <div className='px-4'>
              <SelectInput
                label='Farm'
                value={formik.values.location}
                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}
                isMulti={
                  comparisonTypeOptions.find(
                    (option) => option.value === formik.values.comparisonType
                  )?.value === 'FARM'
                }
                isError={
                  Boolean(formik.errors.location) &&
                  Boolean(formik.touched.location)
                }
              />
            </div>

            {/* Flock */}
            {!(
              formik.values.analysisMode === 'COMPARISON' &&
              !(
                formik.values.comparisonType === 'FLOCK' ||
                formik.values.comparisonType === 'KANDANG'
              )
            ) && (
              <div className='px-4'>
                <SelectInput
                  label='Flock'
                  value={formik.values.flock}
                  onChange={(selected) =>
                    formik.setFieldValue('flock', selected)
                  }
                  errorMessage={formik.errors.flock as string}
                  options={flockOptions}
                  isLoading={isLoadingFlockOptions}
                  isMulti={
                    comparisonTypeOptions.find(
                      (option) => option.value === formik.values.comparisonType
                    )?.value === 'FLOCK'
                  }
                  isError={
                    Boolean(formik.errors.flock) &&
                    Boolean(formik.touched.flock)
                  }
                />
              </div>
            )}

            {/* Kandang */}
            {!(
              formik.values.analysisMode === 'COMPARISON' &&
              !(formik.values.comparisonType === 'KANDANG')
            ) && (
              <div className='px-4'>
                <SelectInput
                  label='Kandang'
                  value={formik.values.kandang}
                  onChange={(selected) =>
                    formik.setFieldValue('kandang', selected)
                  }
                  errorMessage={formik.errors.kandang as string}
                  options={kandangOptions}
                  isLoading={isLoadingKandangOptions}
                  isMulti={
                    comparisonTypeOptions.find(
                      (option) => option.value === formik.values.comparisonType
                    )?.value === 'KANDANG'
                  }
                  isError={
                    Boolean(formik.errors.kandang) &&
                    Boolean(formik.touched.kandang)
                  }
                />
              </div>
            )}

            <AlertErrorList formErrorList={formErrorList} onClose={close} />

            {/* Action Buttons */}
            <div className='flex justify-between gap-4 py-4 mt-8 border-t border-gray-300 bg-gray-100'>
              <Button
                type='reset'
                variant='soft'
                className='ms-4 min-w-36 rounded-lg'
                onClick={handleResetFilter}
              >
                Reset Filter
              </Button>
              <Button type='submit' className='me-4 min-w-36 rounded-lg'>
                Terapkan Filter
              </Button>
            </div>
          </form>
        </div>
      </Modal>
    </>
  );
};

export default DashboardProduction;
