'use client';

import { useMemo, useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Icon } from '@iconify/react';
import { ColumnDef } from '@tanstack/react-table';
import Button from '@/components/Button';
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
import Table from '@/components/Table';
import StatusBadge from '@/components/helper/StatusBadge';
import Tooltip from '@/components/Tooltip';
import RequirePermission from '@/components/helper/RequirePermission';
import { UniformityDetail as UniformityDetailType } from '@/types/api/production/uniformity';
import { formatDate, formatNumber } from '@/lib/helper';
import { useUiStore } from '@/stores/ui/ui.store';
import UniformityDetailsPreview from '@/components/pages/production/uniformity/detail/UniformityDetailsPreview';
import { UniformityApi } from '@/services/api/uniformity';
import useSWR from 'swr';
import { isResponseSuccess } from '@/lib/api-helper';
import {
  getStatusBadgeColor,
  getStatusText,
} from '@/components/pages/production/uniformity/uniformity-utils';
import { DetailOptionType } from '@/types/api/production/uniformity';

interface UniformityDetailProps {
  initialValues: UniformityDetailType;
}

const UniformityDetail: React.FC<UniformityDetailProps> = ({
  initialValues,
}) => {
  const router = useRouter();
  const setExpandedDrawerOpen = useUiStore((s) => s.setExpandedDrawerOpen);
  const setExpandedDrawerContent = useUiStore(
    (s) => s.setExpandedDrawerContent
  );
  const [shouldFetchDetails, setShouldFetchDetails] = useState(false);
  const [hasFetchedDetails, setHasFetchedDetails] = useState(false);

  const { data: uniformityDetailResponse, isLoading } = useSWR(
    shouldFetchDetails
      ? `uniformity-detail-${initialValues.id}-with-details`
      : null,
    () => UniformityApi.getUniformityDetail(initialValues.id, true)
  );

  const uniformity_details = useMemo(() => {
    if (shouldFetchDetails && isResponseSuccess(uniformityDetailResponse)) {
      return uniformityDetailResponse.data.uniformity_details;
    }
    return initialValues.uniformity_details;
  }, [shouldFetchDetails, uniformityDetailResponse, initialValues]);

  const handleApprove = () => {
    router.push(`/production/uniformity?action=approve&id=${initialValues.id}`);
  };

  const handleReject = () => {
    router.push(`/production/uniformity?action=reject&id=${initialValues.id}`);
  };

  const handleViewUniformityDetails = () => {
    if (!uniformity_details || uniformity_details.length === 0) {
      setShouldFetchDetails(true);
      return;
    }

    setExpandedDrawerContent(
      <UniformityDetailsPreview
        info_umum={initialValues.info_umum}
        uniformity_details={uniformity_details}
        uniformityId={initialValues.id}
      />
    );

    setTimeout(() => {
      setExpandedDrawerOpen(true);
    }, 0);
  };

  useEffect(() => {
    if (
      shouldFetchDetails &&
      uniformity_details &&
      uniformity_details.length > 0 &&
      !hasFetchedDetails
    ) {
      setExpandedDrawerContent(
        <UniformityDetailsPreview
          info_umum={initialValues.info_umum}
          uniformity_details={uniformity_details}
          uniformityId={initialValues.id}
        />
      );

      setHasFetchedDetails(true);
      setTimeout(() => {
        setExpandedDrawerOpen(true);
      }, 0);
    }
  }, [
    shouldFetchDetails,
    uniformity_details,
    hasFetchedDetails,
    setExpandedDrawerContent,
    setExpandedDrawerOpen,
    initialValues.info_umum,
    initialValues.id,
  ]);

  useEffect(() => {
    return () => {
      setExpandedDrawerOpen(false);
      setExpandedDrawerContent(null);
    };
  }, [setExpandedDrawerOpen, setExpandedDrawerContent]);

  const infoUmumTableData: DetailOptionType[] = useMemo(() => {
    if (!initialValues) return [];

    return [
      {
        id: 'tanggal',
        value: 'tanggal',
        label: 'Tanggal',
      },
      {
        id: 'lokasi-farm',
        value: 'lokasi-farm',
        label: 'Lokasi Farm',
      },
      {
        id: 'project-flock',
        value: 'project-flock',
        label: 'Project Flock',
      },
      {
        id: 'kandang',
        value: 'kandang',
        label: 'Kandang',
      },
      {
        id: 'document-name',
        value: 'document-name',
        label: 'File Uniformity',
      },
      {
        id: 'approval-status',
        value: 'approval-status',
        label: 'Status',
      },
    ];
  }, [initialValues]);

  const columnsInfoUmum: ColumnDef<DetailOptionType>[] = useMemo(
    () => [
      {
        accessorKey: 'label',
        enableSorting: false,
        header: () => (
          <span className='font-medium text-sm leading-[150%]'>Label</span>
        ),
        cell: (props) => props.row.original.label,
      },
      {
        accessorKey: 'value',
        enableSorting: false,
        header: () => (
          <span className='font-medium text-sm leading-[150%]'>Value</span>
        ),
        cell: (props) => {
          const id = props.row.original.id;
          const { info_umum, latest_approval } = initialValues!;

          const statusValue = latest_approval?.action ?? '-';

          const valueMap: Record<string, string> = {
            tanggal: info_umum?.tanggal
              ? formatDate(info_umum.tanggal, 'DD MMMM YYYY')
              : '-',
            'lokasi-farm': info_umum?.lokasi_farm ?? '-',
            'project-flock': info_umum?.project_flock ?? '-',
            kandang: info_umum?.kandang ?? '-',
            'document-name': info_umum?.file_name ?? '-',
            'approval-status': statusValue,
          };

          if (id === 'approval-status') {
            const status = latest_approval?.action;
            if (status) {
              return (
                <div className='w-full'>
                  <StatusBadge
                    color={getStatusBadgeColor(status)}
                    text={getStatusText(status)}
                  />
                </div>
              );
            }
            return <span>-</span>;
          }

          if (id === 'document-name') {
            return (
              <div className='flex items-center gap-2'>
                <span>{valueMap[id]}</span>
                <Tooltip content='Lihat Detail' position='left'>
                  <button
                    className='p-1 hover:bg-gray-100 rounded cursor-pointer disabled:opacity-50'
                    onClick={handleViewUniformityDetails}
                    disabled={isLoading}
                  >
                    {isLoading ? (
                      <Icon
                        icon='mdi:loading'
                        width={18}
                        height={18}
                        className='animate-spin'
                      />
                    ) : (
                      <Icon icon='mdi:eye-outline' width={18} height={18} />
                    )}
                  </button>
                </Tooltip>
              </div>
            );
          }

          return <span>{valueMap[id] || '-'}</span>;
        },
      },
    ],
    [initialValues, handleViewUniformityDetails, isLoading]
  );

  const samplingTableData: DetailOptionType[] = useMemo(() => {
    if (!initialValues.sampling) return [];

    return [
      {
        id: 'sampling-size',
        label: 'Sampling size',
        value: `${formatNumber(initialValues.sampling.chick_qty_of_weight)} of Birds`,
      },
      {
        id: 'mean-weight',
        label: 'Mean Weight',
        value: `${initialValues.sampling.mean_weight} g`,
      },
      {
        id: 'min-limit',
        label: 'Min Limit (-10%)',
        value: `${initialValues.sampling.mean_down} g`,
      },
      {
        id: 'max-limit',
        label: 'Max Limit (+10%)',
        value: `${initialValues.sampling.mean_up} g`,
      },
    ];
  }, [initialValues.sampling]);

  const columnsSampling: ColumnDef<DetailOptionType>[] = useMemo(
    () => [
      {
        accessorKey: 'label',
        enableSorting: false,
        header: () => (
          <span className='font-medium text-sm leading-[150%]'>Label</span>
        ),
        cell: (props) => props.row.original.label,
      },
      {
        accessorKey: 'value',
        enableSorting: false,
        header: () => (
          <span className='font-medium text-sm leading-[150%]'>Value</span>
        ),
        cell: (props) => <span>{props.row.original.value}</span>,
      },
    ],
    []
  );

  const resultTableData: DetailOptionType[] = useMemo(() => {
    if (!initialValues.result) return [];

    return [
      {
        id: 'ideal-birds',
        label: 'Ideal Birds',
        value: `${formatNumber(initialValues.result.uniform_qty)} of Birds`,
      },
      {
        id: 'outside-range',
        label: 'Outside Range',
        value: `${formatNumber(initialValues.result.outside_qty)} of Birds`,
      },
      {
        id: 'uniformity',
        label: 'Uniformity',
        value: `${initialValues.result.uniformity} %`,
      },
      {
        id: 'cv',
        label: 'CV',
        value: `${initialValues.result.cv} %`,
      },
    ];
  }, [initialValues.result]);

  const resultColumns: ColumnDef<DetailOptionType>[] = useMemo(
    () => [
      {
        accessorKey: 'label',
        enableSorting: false,
        header: () => (
          <span className='font-medium text-sm leading-[150%]'>Label</span>
        ),
        cell: (props) => props.row.original.label,
      },
      {
        accessorKey: 'value',
        enableSorting: false,
        header: () => (
          <span className='font-medium text-sm leading-[150%]'>Value</span>
        ),
        cell: (props) => <span>{props.row.original.value}</span>,
      },
    ],
    []
  );

  return (
    <section className='w-full h-full bg-white border-l border-gray-200'>
      {/* Header */}
      <DrawerHeader
        leftIconHref='/production/uniformity'
        subtitle={`Details`}
        subtitleClassName='text-sm font-medium text-base-content/50'
        showDivider
      />

      {/* Form Section */}
      <section className='w-full p-4'>
        {initialValues ? (
          <div className='flex flex-col gap-3'>
            {/* Info Umum */}
            <div className=''>
              <h2 className='text-base font-medium text-base-content/50 font-roboto leading-6 tracking-[0.15px] mb-1.5'>
                Informasi Umum
              </h2>
              <Table<DetailOptionType>
                data={infoUmumTableData}
                columns={columnsInfoUmum}
                pageSize={6}
                className={{
                  containerClassName: 'mb-0',
                  paginationClassName: 'hidden',
                }}
              />
            </div>

            {/* Sampling and Range */}
            {initialValues.sampling && (
              <div className=''>
                <h2 className='text-base font-medium text-base-content/50 font-roboto leading-6 tracking-[0.15px] mb-1.5'>
                  Sampling and Range
                </h2>
                <Table<DetailOptionType>
                  data={samplingTableData}
                  columns={columnsSampling}
                  pageSize={4}
                  className={{
                    containerClassName: 'mb-0',
                    paginationClassName: 'hidden',
                  }}
                />
              </div>
            )}

            {/* Result */}
            {initialValues.result && (
              <div className=''>
                <h2 className='text-base font-medium text-base-content/50 font-roboto leading-6 tracking-[0.15px] mb-1.5'>
                  Result
                </h2>
                <Table<DetailOptionType>
                  data={resultTableData}
                  columns={resultColumns}
                  pageSize={4}
                  className={{
                    containerClassName: 'mb-0',
                    paginationClassName: 'hidden',
                  }}
                />
              </div>
            )}

            {/* Approve/Reject Buttons */}
            {initialValues.result &&
            initialValues.latest_approval?.step_name === 'CREATED' ? (
              <>
                <div className='divider my-3.5' />
                <RequirePermission permissions='lti.production.uniformity.approve'>
                  <div className='grid grid-cols-1 sm:grid-cols-2 gap-4 [&_button]:rounded-lg'>
                    <Button variant='outline' onClick={handleReject}>
                      Reject
                    </Button>
                    <Button onClick={handleApprove}>Approve</Button>
                  </div>
                </RequirePermission>
              </>
            ) : null}
          </div>
        ) : (
          <div className='flex flex-col items-center justify-center py-10 text-gray-400'>
            <Icon
              icon='mdi:file-document-outline'
              width={64}
              height={64}
              className='mb-4'
            />
            <p className='text-lg'>No data available</p>
            <p className='text-sm'>Uniformity detail not found</p>
          </div>
        )}
      </section>
    </section>
  );
};

export default UniformityDetail;
