'use client';

import { useMemo } from 'react';
import { Icon } from '@iconify/react';
import { ColumnDef } from '@tanstack/react-table';
import Button from '@/components/Button';
import Tooltip from '@/components/Tooltip';
import DrawerHeader from '@/components/helper/drawer/DrawerHeader';
import { useUiStore } from '@/stores/ui/ui.store';
import { useUniformityStore } from '@/stores/production/uniformity/uniformity.store';
import RequirePermission from '@/components/helper/RequirePermission';
import Table from '@/components/Table';
import {
  BodyWeightData,
  UniformityDetailItem,
} from '@/types/api/production/uniformity';

const UniformityPreviewForm = () => {
  const setExpandedDrawerOpen = useUiStore((s) => s.setExpandedDrawerOpen);
  const setIsNextStep = useUiStore((s) => s.setIsNextStep);
  const setUniformityStep = useUniformityStore((s) => s.setUniformityStep);
  const verifyUniformityResult = useUniformityStore(
    (s) => s.verifyUniformityResult
  );
  const uniformityFormData = useUniformityStore((s) => s.uniformityFormData);

  const handleClose = () => {
    setExpandedDrawerOpen(false);
    setIsNextStep(false);
    setUniformityStep('preview');
  };

  const handleNext = () => {
    setUniformityStep('result');
  };

  const tableData = useMemo(() => {
    if (!verifyUniformityResult) return [];

    return verifyUniformityResult.uniformity_details.map(
      (detail: UniformityDetailItem, index: number) => ({
        id: `weight-${index}`,
        number: index + 1,
        weight: detail.weight,
      })
    );
  }, [verifyUniformityResult]);

  const columns: ColumnDef<BodyWeightData>[] = useMemo(
    () => [
      {
        accessorKey: 'number',
        header: () => (
          <span className='font-medium text-sm leading-[150%]'>Number</span>
        ),
        cell: (props) => props.row.original.number,
      },
      {
        accessorKey: 'weight',
        header: () => (
          <span className='font-medium text-sm leading-[150%]'>Weight (g)</span>
        ),
        cell: (props) => <span>{props.row.original.weight}</span>,
      },
    ],
    []
  );

  return (
    <section className='w-full h-full bg-white border-l border-gray-200'>
      {/* Header */}
      <DrawerHeader
        leftIcon=''
        subtitle={uniformityFormData?.file_name || 'Add Body Weight'}
        subtitleClassName='text-sm font-medium text-base-content/50 line-clamp-1'
        showDivider={false}
      >
        <Button variant='link' className='p-0 text-error' onClick={handleClose}>
          <Tooltip content='Hapus' position='left'>
            <Icon icon='heroicons-outline:trash' width={18} height={18} />
          </Tooltip>
        </Button>
      </DrawerHeader>

      {/* Form Section */}
      <section className='w-full p-4'>
        {verifyUniformityResult ? (
          <div className='flex flex-col gap-4'>
            <Table<BodyWeightData>
              data={tableData}
              columns={columns}
              pageSize={15}
              className={{ containerClassName: 'mb-5' }}
            />
            <RequirePermission permissions='lti.production.uniformity.create'>
              <Button
                color='primary'
                onClick={handleNext}
                className='mb-5 px-3 py-2.5 text-sm text-base-100 rounded-lg shadow-sm'
              >
                Next
              </Button>
            </RequirePermission>
          </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'>Upload a file to verify uniformity</p>
          </div>
        )}
      </section>
    </section>
  );
};

export default UniformityPreviewForm;
