'use client';

import { useMemo } from 'react';
import { Card, CardContent } from '@/figma-make/components/base/card';
import { Label } from '@/figma-make/components/base/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/figma-make/components/base/select';
import { useSelect } from '@/components/input/SelectInput';
import { AreaApi, LocationApi } from '@/services/api/master-data';
import useSWR from 'swr';
import { BaseApiResponse } from '@/types/api/api-general';
import { DailyChecklistReport } from '@/types/api/daily-checklist/daily-checklist';
import { AxiosError } from 'axios';
import { httpClientFetcher, SWRHttpKey } from '@/services/http/client';
import { DailyChecklistApi } from '@/services/api/daily-checklist/daily-checklist';
import Table from '@/components/Table';
import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter';
import { cn } from '@/lib/helper';
import { ColumnDef } from '@tanstack/react-table';
import { PhaseApi } from '@/services/api/daily-checklist/phase';
import { EmployeeApi } from '@/services/api/daily-checklist/employee';
import { Button } from '@/figma-make/components/base/button';
import { Download, Loader2 } from 'lucide-react';
import { DailyChecklistKandangApi } from '@/services/api/daily-checklist/kandang';

const MONTH_OPTIONS = [
  { value: '1', label: 'Januari' },
  { value: '2', label: 'Februari' },
  { value: '3', label: 'Maret' },
  { value: '4', label: 'April' },
  { value: '5', label: 'Mei' },
  { value: '6', label: 'Juni' },
  { value: '7', label: 'Juli' },
  { value: '8', label: 'Agustus' },
  { value: '9', label: 'September' },
  { value: '10', label: 'Oktober' },
  { value: '11', label: 'November' },
  { value: '12', label: 'Desember' },
];

const YEAR_OPTIONS = [
  { value: '2027', label: '2027' },
  { value: '2026', label: '2026' },
  { value: '2025', label: '2025' },
  { value: '2024', label: '2024' },
  { value: '2023', label: '2023' },
  { value: '2022', label: '2022' },
  { value: '2021', label: '2021' },
  { value: '2020', label: '2020' },
];

// const CATEGORY_LABELS: { [key: string]: string } = {
//   pullet_open: 'Pullet Open',
//   pullet_close: 'Pullet Close',
//   produksi_open: 'Produksi Open',
//   produksi_close: 'Produksi Close',
// };

export function DailyChecklistReportsContent() {
  const currentMonth = useMemo(() => new Date().getMonth() + 1, []);
  const currentYear = useMemo(() => new Date().getFullYear(), []);

  const {
    state: tableFilterState,
    updateFilter,
    setPage,
    setPageSize,
    toQueryString: getTableFilterQueryString,
  } = useTableFilter({
    initial: {
      bulan: currentMonth.toString(),
      tahun: currentYear.toString(),
      area_id: '',
      location_id: '',
      kandang_id: '',
      employee_id: '',
      phase_id: '',
    },
    paramMap: {
      page: 'page',
      pageSize: 'limit',
      bulan: 'bulan',
      tahun: 'tahun',
      area_id: 'area_id',
      location_id: 'location_id',
      kandang_id: 'kandang_id',
      employee_id: 'employee_id',
      phase_id: 'phase_id',
    },
  });

  const { data: reportResponse, isLoading: isLoadingReport } = useSWR<
    BaseApiResponse<DailyChecklistReport[] | undefined>,
    AxiosError<BaseApiResponse>,
    SWRHttpKey
  >(
    `${DailyChecklistApi.basePath}/report${getTableFilterQueryString()}`,
    httpClientFetcher,
    {
      keepPreviousData: true,
    }
  );

  const { options: areaOptions } = useSelect(
    AreaApi.basePath,
    'id',
    'name',
    'search',
    {
      page: '1',
      limit: '100',
    }
  );

  const { options: locationOptions } = useSelect(
    LocationApi.basePath,
    'id',
    'name',
    'search',
    {
      page: '1',
      limit: '100',
      area_id: tableFilterState.area_id,
    }
  );

  const {
    options: kandangOptions,
    loadMore: loadMoreKandang,
    isLoadingMore: isLoadingMoreKandang,
  } = useSelect(DailyChecklistKandangApi.basePath, 'id', 'name', 'search', {
    area_id: tableFilterState.area_id,
    location_id: tableFilterState.location_id,
    order_by: 'asc',
    sort_by: 'name',
  });

  const handleKandangScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const target = e.target as HTMLDivElement;
    if (target.scrollHeight - target.scrollTop <= target.clientHeight + 10) {
      if (!isLoadingMoreKandang) {
        loadMoreKandang();
      }
    }
  };

  const { options: phaseOptions } = useSelect(
    PhaseApi.basePath,
    'id',
    'name',
    'search',
    {
      page: '1',
      limit: '100',
    }
  );

  const {
    options: employeeOptions,
    loadMore: loadMoreEmployee,
    isLoadingMore: isLoadingMoreEmployee,
  } = useSelect(EmployeeApi.basePath, 'id', 'name', 'search', {
    order_by: 'asc',
    sort_by: 'name',
    kandang_id: tableFilterState.kandang_id,
  });

  const handleEmployeeScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const target = e.target as HTMLDivElement;
    if (target.scrollHeight - target.scrollTop <= target.clientHeight + 10) {
      if (!isLoadingMoreEmployee) {
        loadMoreEmployee();
      }
    }
  };

  const currentMonthMaxDay = new Date(
    Number(tableFilterState.tahun),
    Number(tableFilterState.bulan),
    0
  ).getDate();

  const reportDateColumns: ColumnDef<DailyChecklistReport>[] = [];

  if (isResponseSuccess(reportResponse) && reportResponse.data) {
    for (let dateNumber = 1; dateNumber <= currentMonthMaxDay; dateNumber++) {
      reportDateColumns.push({
        accessorKey: `daily_activities[${dateNumber}]`,
        header: `${dateNumber}`,
        enableSorting: false,
        cell: ({ row }) => row.original.daily_activities[dateNumber],
      });
    }
  }

  const reportColumns: ColumnDef<DailyChecklistReport>[] = [
    {
      accessorKey: 'area',
      header: 'Area',
      enableSorting: false,
      cell: ({ row }) => row.original.area.name,
    },
    {
      accessorKey: 'farm',
      header: 'Farm',
      enableSorting: false,
      cell: ({ row }) => row.original.farm.name,
    },
    {
      accessorKey: 'kandang',
      header: 'Kandang',
      enableSorting: false,
      cell: ({ row }) => row.original.kandang.name,
    },
    {
      accessorKey: 'abk',
      header: 'ABK',
      enableSorting: false,
      cell: ({ row }) => (
        <span className='text-nowrap'>{row.original.abk.name}</span>
      ),
    },
    {
      accessorKey: 'phase',
      header: 'Phase',
      enableSorting: false,
      cell: ({ row }) => row.original.phase,
    },
    {
      header: `Tanggal - ${MONTH_OPTIONS[Number(tableFilterState.bulan) - 1].label} - ${tableFilterState.tahun}`,
      columns: reportDateColumns,
    },
    {
      accessorKey: 'summary.total_checklist',
      header: 'Total Checklist',
      enableSorting: false,
    },
    {
      accessorKey: 'summary.jumlah_hari_efektif',
      header: 'Jumlah Hari Efektif',
      enableSorting: false,
    },
    {
      accessorKey: 'summary.abk_percentage',
      header: 'ABK (%)',
      enableSorting: false,
    },
    {
      accessorKey: 'summary.kandang_percentage',
      header: 'Kandang (%)',
      enableSorting: false,
    },
    {
      header: 'Kategori',
      columns: [
        {
          accessorKey: 'summary.kategori.kurang',
          header: 'Kurang',
          enableSorting: false,
          cell: ({ row }) => (
            <span className='text-red-400'>
              {row.original.summary.kategori.kurang}
            </span>
          ),
        },
        {
          accessorKey: 'summary.kategori.cukup',
          header: 'Cukup',
          enableSorting: false,
          cell: ({ row }) => row.original.summary.kategori.cukup,
        },
        {
          accessorKey: 'summary.kategori.baik',
          header: 'Baik',
          enableSorting: false,
          cell: ({ row }) => (
            <span className='text-green-400'>
              {row.original.summary.kategori.baik}
            </span>
          ),
        },
      ],
    },
  ];

  const exportToCSV = () => {
    DailyChecklistApi.exportDailyChecklistReportToExcel(
      getTableFilterQueryString()
    );
  };

  const monthChangeHandler = (value: string) => updateFilter('bulan', value);
  const yearChangeHandler = (value: string) => updateFilter('tahun', value);

  const areaChangeHandler = (value: string) => {
    updateFilter('area_id', value === 'ALL' ? '' : value);
    updateFilter('location_id', '');
    updateFilter('kandang_id', '');
    updateFilter('employee_id', '');
  };

  const locationChangeHandler = (value: string) => {
    updateFilter('location_id', value === 'ALL' ? '' : value);
    updateFilter('kandang_id', '');
    updateFilter('employee_id', '');
  };

  const kandangChangeHandler = (value: string) => {
    updateFilter('kandang_id', value === 'ALL' ? '' : value);
    updateFilter('employee_id', '');
  };

  const phaseChangeHandler = (value: string) => {
    updateFilter('phase_id', value === 'ALL' ? '' : value);
  };

  const employeeChangeHandler = (value: string) => {
    updateFilter('employee_id', value === 'ALL' ? '' : value);
  };

  return (
    <div className='min-h-screen'>
      <div className='p-6'>
        {/* Page Title */}
        <div className='mb-6 flex items-center justify-between'>
          <div>
            <h1 className='text-2xl font-semibold text-gray-900'>Reports</h1>
            <p className='text-sm text-gray-600 mt-1'>
              Laporan lengkap checklist harian
            </p>
          </div>
          <Button
            onClick={exportToCSV}
            className='bg-[#0069e0] hover:bg-[#0058c0] text-white'
          >
            <Download className='w-4 h-4 mr-2' />
            Export CSV
          </Button>
        </div>

        {/* Main Card */}
        <Card className='border-gray-200/60 shadow-sm rounded-xl bg-white'>
          <CardContent className='p-6'>
            {/* Filters Section */}
            <div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 pb-6 border-b border-gray-200'>
              <div>
                <Label htmlFor='bulan-filter-report'>Bulan</Label>
                <Select
                  value={tableFilterState.bulan}
                  onValueChange={monthChangeHandler}
                >
                  <SelectTrigger
                    id='bulan-filter-report'
                    className='mt-1.5 border-gray-200'
                  >
                    <SelectValue placeholder='Semua Bulan' />
                  </SelectTrigger>
                  <SelectContent>
                    {MONTH_OPTIONS.map((bulan) => (
                      <SelectItem key={bulan.value} value={String(bulan.value)}>
                        {bulan.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor='tahun-filter-report'>Tahun</Label>
                <Select
                  value={tableFilterState.tahun}
                  onValueChange={yearChangeHandler}
                >
                  <SelectTrigger
                    id='tahun-filter-report'
                    className='mt-1.5 border-gray-200'
                  >
                    <SelectValue placeholder='Semua Tahun' />
                  </SelectTrigger>
                  <SelectContent>
                    {YEAR_OPTIONS.map((tahun) => (
                      <SelectItem key={tahun.value} value={String(tahun.value)}>
                        {tahun.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor='area-filter-report'>Area</Label>
                <Select
                  value={tableFilterState.area_id}
                  onValueChange={areaChangeHandler}
                >
                  <SelectTrigger
                    id='area-filter-report'
                    className='mt-1.5 border-gray-200'
                  >
                    <SelectValue placeholder='Semua Area' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='ALL'>Semua Area</SelectItem>
                    {areaOptions.map((area) => (
                      <SelectItem key={area.value} value={String(area.value)}>
                        {area.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor='location-filter-report'>Lokasi</Label>
                <Select
                  value={tableFilterState.location_id}
                  onValueChange={locationChangeHandler}
                >
                  <SelectTrigger
                    id='location-filter-report'
                    className='mt-1.5 border-gray-200'
                  >
                    <SelectValue placeholder='Semua Lokasi' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='ALL'>Semua Lokasi</SelectItem>
                    {locationOptions.map((location) => (
                      <SelectItem
                        key={location.value}
                        value={String(location.value)}
                      >
                        {location.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor='kandang-filter-report'>Kandang</Label>
                <Select
                  value={tableFilterState.kandang_id}
                  onValueChange={kandangChangeHandler}
                >
                  <SelectTrigger
                    id='kandang-filter-report'
                    className='mt-1.5 border-gray-200'
                  >
                    <SelectValue placeholder='Semua Kandang' />
                  </SelectTrigger>
                  <SelectContent onScroll={handleKandangScroll}>
                    <SelectItem value='ALL'>Semua Kandang</SelectItem>
                    {kandangOptions.map((kandang) => (
                      <SelectItem
                        key={kandang.value}
                        value={String(kandang.value)}
                      >
                        {kandang.label}
                      </SelectItem>
                    ))}
                    {isLoadingMoreKandang && (
                      <div className='flex justify-center p-2'>
                        <Loader2 className='h-4 w-4 animate-spin text-gray-500' />
                      </div>
                    )}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor='phase-filter-report'>Phase</Label>
                <Select
                  value={tableFilterState.phase_id}
                  onValueChange={phaseChangeHandler}
                >
                  <SelectTrigger
                    id='phase-filter-report'
                    className='mt-1.5 border-gray-200'
                  >
                    <SelectValue placeholder='Semua Phase' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='ALL'>Semua Phase</SelectItem>
                    {phaseOptions.map((phase) => (
                      <SelectItem key={phase.value} value={String(phase.value)}>
                        {phase.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor='employee-filter-report'>ABK</Label>
                <Select
                  value={tableFilterState.employee_id}
                  onValueChange={employeeChangeHandler}
                >
                  <SelectTrigger
                    id='employee-filter-report'
                    className='mt-1.5 border-gray-200'
                  >
                    <SelectValue placeholder='Semua ABK' />
                  </SelectTrigger>
                  <SelectContent onScroll={handleEmployeeScroll}>
                    <SelectItem value='ALL'>Semua ABK</SelectItem>
                    {employeeOptions.map((employee) => (
                      <SelectItem
                        key={employee.value}
                        value={String(employee.value)}
                      >
                        {employee.label}
                      </SelectItem>
                    ))}
                    {isLoadingMoreEmployee && (
                      <div className='flex justify-center p-2'>
                        <Loader2 className='h-4 w-4 animate-spin text-gray-500' />
                      </div>
                    )}
                  </SelectContent>
                </Select>
              </div>
            </div>

            {/* Reports Table */}
            <Table<DailyChecklistReport>
              data={
                isResponseSuccess(reportResponse)
                  ? reportResponse.data || []
                  : []
              }
              columns={reportColumns}
              isLoading={isLoadingReport}
              pageSize={tableFilterState.pageSize}
              onPageSizeChange={setPageSize}
              rowOptions={[10, 20, 50, 100]}
              page={
                isResponseSuccess(reportResponse)
                  ? reportResponse?.meta?.page
                  : 0
              }
              totalItems={
                isResponseSuccess(reportResponse)
                  ? reportResponse?.meta?.total_results
                  : 0
              }
              onPageChange={setPage}
              className={{
                containerClassName: cn({
                  'w-full mb-20':
                    isResponseSuccess(reportResponse) &&
                    reportResponse?.data?.length === 0,
                }),
                tableWrapperClassName:
                  'overflow-x-auto border border-solid border-base-content/10 rounded-none',
                headerRowClassName: 'bg-gray-50/50',
                headerColumnClassName:
                  'text-left py-3.5 px-6 text-sm font-semibold text-gray-700 border-x border-base-content/10',
                bodyColumnClassName:
                  'px-4 py-3 text-base-content border-x border-base-content/10',
                paginationClassName: 'px-4',
              }}
            />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
