'use client';

import React, { 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 { useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import { UniformityApi } from '@/services/api/uniformity';
import { isResponseError } from '@/lib/api-helper';
import StatusBadge from '@/components/helper/StatusBadge';
import { formatNumber } from '@/lib/helper';
import {
  getWeightStatusText,
  getWeightStatusBadgeColor,
} from '@/components/pages/production/uniformity/uniformity-utils';
import { DetailOptionType } from '@/types/api/production/uniformity';
import {
  BodyWeightData,
  UniformityDetailItem,
} from '@/types/api/production/uniformity';

const UniformityResultForm = () => {
  const router = useRouter();
  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 setVerifyUniformityResult = useUniformityStore(
    (s) => s.setVerifyUniformityResult
  );
  const uniformityFormData = useUniformityStore((s) => s.uniformityFormData);
  const setIsSuccess = useUniformityStore((s) => s.setIsSuccess);
  const setCreatedUniformity = useUniformityStore(
    (s) => s.setCreatedUniformity
  );

  const [isSubmitting, setIsSubmitting] = React.useState(false);

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

  const handleSubmit = async () => {
    if (!uniformityFormData || !uniformityFormData.document) {
      toast.error('Form data is missing. Please try again.');
      return;
    }

    setIsSubmitting(true);

    try {
      const payload = {
        date: uniformityFormData.date,
        project_flock_kandang_id: uniformityFormData.project_flock_kandang_id,
        document: uniformityFormData.document,
      };

      const res = await UniformityApi.createUniformity(payload);

      if (!res || isResponseError(res)) {
        toast.error(res?.message || 'Failed to create uniformity');
        return;
      }

      setCreatedUniformity(res.data);
      setIsSuccess(true);
      setExpandedDrawerOpen(false);
      setIsNextStep(false);
      setUniformityStep('preview');
      setVerifyUniformityResult(null);
      router.push('/production/uniformity');
    } finally {
      setIsSubmitting(false);
    }
  };

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

    const { sampling } = verifyUniformityResult;

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

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

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

    const { result } = verifyUniformityResult;

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

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

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

    return verifyUniformityResult.uniformity_details.map(
      (detail: UniformityDetailItem, index: number) => ({
        id: `body-weight-${index + 1}`,
        number: index + 1,
        weight: detail.weight,
        status: detail.range.toLowerCase() as 'ideal' | 'outside',
      })
    );
  }, [verifyUniformityResult]);

  const columnsUniformity: ColumnDef<BodyWeightData>[] = useMemo(
    () => [
      {
        accessorKey: 'number',
        header: 'Number',
        cell: (props) => props.row.original.number,
      },
      {
        accessorKey: 'weight',
        header: 'Weight (g)',
        cell: (props) => <span>{props.row.original.weight}</span>,
      },
      {
        accessorKey: 'status',
        header: 'Status',
        cell: (props) => {
          const status = props.row.original.status;
          return status ? (
            <StatusBadge
              color={getWeightStatusBadgeColor(status)}
              text={getWeightStatusText(status)}
            />
          ) : (
            <StatusBadge color='info' text='Unknown' />
          );
        },
      },
    ],
    []
  );

  return (
    <section className='w-full h-full bg-white border-l border-gray-200'>
      {/* Header */}
      <DrawerHeader
        leftIcon=''
        subtitle={uniformityFormData?.document_name || 'Uniformity Result'}
        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-3'>
            <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>

            <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={3}
                className={{
                  containerClassName: 'mb-0',
                  paginationClassName: 'hidden',
                }}
              />
            </div>
            <div className=''>
              <Table<BodyWeightData>
                data={tableData}
                columns={columnsUniformity}
                pageSize={15}
                className={{ containerClassName: 'mb-5' }}
              />
            </div>
            {/* Action Buttons */}
            <RequirePermission permissions='lti.production.uniformity.create'>
              <Button
                color='primary'
                onClick={handleSubmit}
                isLoading={isSubmitting}
                disabled={!uniformityFormData}
                className='mb-5 px-3 py-2.5 text-sm text-base-100 rounded-lg shadow-sm'
              >
                Submit
              </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 UniformityResultForm;
