'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/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 Badge from '@/components/Badge';
import { formatNumber } from '@/lib/helper';
import {
  getWeightStatusColor,
  getWeightStatusIndicatorColor,
  getWeightStatusText,
} 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,
        week: uniformityFormData.week,
        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: 'Label',
        cell: (props) => props.row.original.label,
      },
      {
        accessorKey: 'value',
        header: 'Value',
        cell: (props) => <span>{props.row.original.value}</span>,
      },
    ],
    []
  );

  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: 'Label',
        cell: (props) => props.row.original.label,
      },
      {
        accessorKey: 'value',
        header: 'Value',
        cell: (props) => <span>{props.row.original.value}</span>,
      },
    ],
    []
  );

  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: 'No',
        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 ? (
            <div className='w-full'>
              <Badge
                statusIndicator={true}
                variant='soft'
                className={{
                  badge: `rounded-xl w-full justify-start border border-gray-200 text-black ${getWeightStatusColor(status)}`,
                  status: getWeightStatusIndicatorColor(status),
                }}
              >
                {getWeightStatusText(status)}
              </Badge>
            </div>
          ) : (
            <Badge
              statusIndicator={true}
              variant='soft'
              className={{
                badge:
                  'rounded-xl w-full justify-start border border-gray-200 text-black bg-info/10',
                status: 'bg-info',
              }}
            >
              Unknown
            </Badge>
          );
        },
      },
    ],
    []
  );

  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 text-neutral line-clamp-1'
        showDivider={false}
      >
        <Button variant='link' className='p-0 text-error' onClick={handleClose}>
          <Tooltip content='Hapus' position='left'>
            <Icon icon='mdi:trash-can-outline' width={20} height={20} />
          </Tooltip>
        </Button>
      </DrawerHeader>

      {/* Form Section */}
      <div className='divider mt-3.5'></div>
      <section className='w-full px-6'>
        {verifyUniformityResult ? (
          <div className='flex flex-col gap-4'>
            <div className=''>
              <p className='text-sm font-medium mb-5'>Sampling and Range</p>
              <Table<DetailOptionType>
                data={samplingTableData}
                columns={columnsSampling}
                pageSize={4}
                className={{
                  containerClassName: 'mb-0',
                  paginationClassName: 'hidden',
                }}
              />
            </div>

            <div className=''>
              <p className='text-sm font-medium mb-5'>Result</p>
              <Table<DetailOptionType>
                data={resultTableData}
                columns={resultColumns}
                pageSize={3}
                className={{
                  containerClassName: 'mb-0',
                  paginationClassName: 'hidden',
                }}
              />
            </div>
            <div className='mt-4'>
              <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-10'
              >
                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;
