import { useEffect, useState } from 'react';
import {
  Button,
  Input,
  Popconfirm,
  Popover,
  Space,
  Spin,
  Table,
  message,
  Tag,
} from 'antd';
import {
  PlusOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';
import { StockAllocationModal } from './components/StockAllocationModal';

export const StockAllocation = () => {
  const [searchText, setSearchText] = useState('');
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [closingId, setClosingId] = useState<string | null>(null);

  const handleCloseLot = async (record: any) => {
    setClosingId(record.id);
    try {
      const res = await jwtAxios.patch(ENDPOINTS.RETAIL_STOCK_CLOSE, {
        id: record.id,
        lotNo: record.lotNo,
      });
      message.success(res.data?.message || 'Retail lot closed successfully');
      fetchData(pagination.current, pagination.pageSize, searchText);
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to close retail lot');
    } finally {
      setClosingId(null);
    }
  };
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: Number(import.meta.env.VITE_PAGE_SIZE) || 10,
    total: 0,
    totalPages: 0,
  });

  const fetchData = async (
    page: number = pagination.current,
    limit: number = pagination.pageSize,
    search: string = searchText
  ) => {
    setLoading(true);

    try {
      const url = `${ENDPOINTS.RETAIL_STOCK_ALLOCATIONS}?page=${page}&limit=${limit}&search=${search}`;
      const res = await jwtAxios.get(url);

      const records = res.data?.result?.data || [];
      const metaInfo = res.data?.result?.meta || {};

      const formattedData = records.map((item: any) => ({
        key: item.id,
        ...item,
      }));

      setData(formattedData);
      setPagination((prev) => ({
        ...prev,
        current: metaInfo.page ?? page,
        pageSize: metaInfo.limit ?? limit,
        total: metaInfo.total ?? prev.total,
        totalPages: metaInfo.totalPages ?? prev.totalPages,
      }));
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to fetch allocations');
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData(1, pagination.pageSize, '');
  }, []);

  const handleSearch = (value: string) => {
    fetchData(1, pagination.pageSize, value);
  };

  const columns = [
    {
      title: 'S.No',
      render: (_: any, __: any, index: number) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: 'Retail Lot No',
      dataIndex: 'lotNo',
      ellipsis: true,
      render: (text: string) => <Tag color="blue">{text}</Tag>
    },
    {
      title: 'Allocation Date',
      dataIndex: 'allocationDate',
      ellipsis: true,
      render: (date: string) => date ? dayjs(date).format('DD MMM YYYY') : '-',
    },
    {
      title: 'Source Purchase',
      render: (_: any, record: any) => record.purchase?.lotNo || '-',
    },
    {
      title: 'Vegetable',
      render: (_: any, record: any) => record.purchase?.vegetable?.name || '-',
    },
    {
      title: 'Supplier',
      render: (_: any, record: any) =>
        record.purchase?.supplier?.name || record.purchase?.cashSupplierName || '-',
    },
    {
      title: 'Allocated Qty',
      render: (_: any, record: any) => (
        <span>{Number(record.allocatedQty)} {record.allocatedUnit}</span>
      ),
    },
    {
      title: 'Converted KG',
      render: (_: any, record: any) => (
        <Tag color="purple">{Number(record.quantity)} KG</Tag>
      ),
    },
    {
      title: 'Bags / Boxes / Thaar',
      render: (_: any, record: any) => {
        const bags = record.bags !== null && record.bags !== undefined ? Number(record.bags) : null;
        if (bags === null) return <span style={{ color: '#aaa' }}>-</span>;
        return <Tag color="orange">{bags} {record.purchase?.unit || record.allocatedUnit}</Tag>;
      },
    },
    {
      title: 'Remaining',
      render: (_: any, record: any) => {
        const remaining = Number(record.remainingQuantity);
        const remainingBags = record.remainingBags !== null && record.remainingBags !== undefined
          ? Number(record.remainingBags) : null;
        const color = remaining === 0 ? 'red' : 'green';
        return (
          <span>
            <Tag color={color}>{remaining} KG</Tag>
            {remainingBags !== null && (
              <Tag color={remainingBags === 0 ? 'red' : 'blue'}>{remainingBags} {record.allocatedUnit}</Tag>
            )}
          </span>
        );
      },
    },
    {
      title: 'Remarks',
      dataIndex: 'remarks',
      width: 160,
      ellipsis: true,
      render: (text: string) =>
        text ? (
          <Popover
            title="Remarks"
            content={
              <div style={{ maxWidth: 300, whiteSpace: 'pre-wrap' }}>
                {text}
              </div>
            }
          >
            <span style={{ cursor: 'pointer' }}>{text}</span>
          </Popover>
        ) : (
          '-'
        ),
    },
    {
      title: 'Actions',
      key: 'actions',
      align: 'center' as const,
      render: (_: any, record: any) => {
        const remainingKg = Number(record.remainingQuantity ?? 0);
        const remainingBags = record.remainingBags !== null && record.remainingBags !== undefined
          ? Number(record.remainingBags)
          : 0;
        const hasStock = remainingKg > 0 || remainingBags > 0;
        const isFlexible = !!record.purchase?.vegetable?.isFlexible || record.allocatedUnit === 'THAAR' || record.purchase?.unit === 'THAAR';

        if (!isFlexible) return '-';

        return hasStock ? (
          <Popover content="Close Flexible Lot (Deplete remaining retail stock)">
            <Popconfirm
              title="Close Flexible Lot"
              description={`Are you sure you want to close retail lot "${record.lotNo}"? Remaining balance will be cleared and it will no longer be available for retail sale.`}
              okText="Yes, Close Lot"
              cancelText="Cancel"
              okButtonProps={{ danger: true }}
              onConfirm={() => handleCloseLot(record)}
            >
              <Button
                size="small"
                icon={<CheckCircleOutlined />}
                loading={closingId === record.id}
                style={{ color: '#d97706', borderColor: '#f59e0b' }}
              >
                Close Lot
              </Button>
            </Popconfirm>
          </Popover>
        ) : (
          <Tag color="default">Closed</Tag>
        );
      },
    },
  ];

  return (
    <div>
      <Spin spinning={loading}>
        <AppContainer
          title="Stock Allocation"
          headerAction={
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setModalOpen(true)}
            >
              Allocate Stock
            </Button>
          }
        >
          {/* Toolbar Section */}
          <div className="flex justify-between items-center mb-4 pb-4 border-b border-gray-200">
            <Space>
              <Input.Search
                placeholder="Search by Lot No..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onSearch={handleSearch}
                allowClear
                style={{ width: 250 }}
              />
            </Space>
          </div>

          {/* Table Section */}
          <Table
            rowKey="key"
            columns={columns}
            dataSource={data}
            loading={loading}
            scroll={{ x: 'max-content', y: 400 }}
            pagination={{
              current: pagination.current,
              pageSize: pagination.pageSize,
              total: pagination.total,
              showSizeChanger: true,
            }}
            onChange={(pageInfo) => {
              fetchData(pageInfo.current!, pageInfo.pageSize!, searchText);
            }}
          />
          <div className="text-center mt-2">
            <Tag color="cyan">
              Page {pagination.current} of {pagination.totalPages}
            </Tag>
          </div>
        </AppContainer>

        <StockAllocationModal
          open={modalOpen}
          onCancel={() => setModalOpen(false)}
          onSuccess={() => {
            setModalOpen(false);
            fetchData(1, pagination.pageSize, searchText);
          }}
        />
      </Spin>
    </div>
  );
};
