'use client';

import { useMemo, useEffect } 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 Badge from '@/components/Badge';
import Tooltip from '@/components/Tooltip';
import RequirePermission from '@/components/helper/RequirePermission';
import { UniformityDetail as UniformityDetailType } from '@/types/api/uniformity/uniformity';
import { formatDate } from '@/lib/helper';
import { useUiStore } from '@/stores/ui/ui.store';
import UniformityDetailsPreview from './UniformityDetailsPreview';
import {
  getStatusColor,
  getStatusIndicatorColor,
  getStatusText,
} from '@/components/pages/uniformity/uniformity-utils';
import { DetailOptionType } from '@/types/api/uniformity/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 handleApprove = () => {
    router.push(`/uniformity?action=approve&id=${initialValues.id}`);
  };

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

  const handleViewUniformityDetails = () => {
    setExpandedDrawerContent(
      <UniformityDetailsPreview
        info_umum={initialValues.info_umum}
        uniformity_details={initialValues.uniformity_details}
        sampling={initialValues.sampling}
        result={initialValues.result}
      />
    );

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

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

  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: 'file-name',
        value: 'file-name',
        label: 'File Uniformity',
      },
      {
        id: 'approval-status',
        value: 'approval-status',
        label: 'Status',
      },
    ];
  }, [initialValues]);

  const columnsInfoUmum: ColumnDef<DetailOptionType>[] = useMemo(
    () => [
      {
        accessorKey: 'label',
        header: 'Label',
        cell: (props) => props.row.original.label,
      },
      {
        accessorKey: 'value',
        header: 'Value',
        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: formatDate(info_umum.tanggal, 'DD MMMM YYYY'),
            'lokasi-farm': info_umum.lokasi_farm,
            'project-flock': info_umum.project_flock,
            kandang: info_umum.kandang,
            'file-name': info_umum.file_name,
            'approval-status': statusValue,
          };

          if (id === 'approval-status') {
            const status = latest_approval?.action;
            if (status) {
              return (
                <div className='w-full'>
                  <Badge
                    statusIndicator={true}
                    variant='soft'
                    className={{
                      badge: `rounded-xl w-full justify-start border border-gray-200 text-black ${getStatusColor(status)}`,
                      status: getStatusIndicatorColor(status),
                    }}
                  >
                    {getStatusText(status)}
                  </Badge>
                </div>
              );
            }
            return <span>-</span>;
          }

          if (id === 'file-name') {
            return (
              <div className='flex items-center gap-2'>
                <span>{valueMap[id]}</span>
                <Tooltip content='Lihat Detail'>
                  <button
                    className='p-1 hover:bg-gray-100 rounded'
                    onClick={handleViewUniformityDetails}
                  >
                    <Icon icon='mdi:eye-outline' width={18} height={18} />
                  </button>
                </Tooltip>
              </div>
            );
          }

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

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

      {/* Form Section */}
      <div className='divider mt-3.5'></div>
      <section className='w-full px-6'>
        {initialValues ? (
          <div className='flex flex-col gap-4'>
            {/* Info Umum */}
            <div className=''>
              <p className='text-sm font-medium mb-5'>Informasi Umum</p>
              <Table<DetailOptionType>
                data={infoUmumTableData}
                columns={columnsInfoUmum}
                pageSize={6}
                className={{
                  containerClassName: 'mb-0',
                  paginationClassName: 'hidden',
                }}
              />

              <div className='divider my-3.5' />
              {/* Approve/Reject Buttons */}
              {initialValues.result && (
                <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>
              )}
            </div>
          </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;
