import { useEffect, useState } from 'react';
import { Tabs, Table, Tag, DatePicker, Select, Button, message, Modal, Descriptions, Popover } from 'antd';
import { EyeOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';

const { RangePicker } = DatePicker;

export default function SpoilsReturns() {
  const [activeTab, setActiveTab] = useState('spoils');

  // Meta data for filters
  const [vegetables, setVegetables] = useState<any[]>([]);
  const [customers, setCustomers] = useState<any[]>([]);

  // Wholesale Spoilage history state
  const [spoilsData, setSpoilsData] = useState<any[]>([]);
  const [spoilsLoading, setSpoilsLoading] = useState(false);
  const [selectedVeg, setSelectedVeg] = useState<string | undefined>(undefined);
  const [spoilsDateRange, setSpoilsDateRange] = useState<any>(null);

  // Retail Spoilage history state
  const [retailSpoilsData, setRetailSpoilsData] = useState<any[]>([]);
  const [retailSpoilsLoading, setRetailSpoilsLoading] = useState(false);
  const [selectedRetailVeg, setSelectedRetailVeg] = useState<string | undefined>(undefined);
  const [retailSpoilsDateRange, setRetailSpoilsDateRange] = useState<any>(null);

  // Return history state
  const [returnsData, setReturnsData] = useState<any[]>([]);
  const [returnsLoading, setReturnsLoading] = useState(false);
  const [selectedCustomer, setSelectedCustomer] = useState<string | undefined>(undefined);
  const [returnsDateRange, setReturnsDateRange] = useState<any>(null);

  // View modal state
  const [viewOpen, setViewOpen] = useState(false);
  const [viewRecord, setViewRecord] = useState<any>(null);
  const [viewType, setViewType] = useState<'wholesale' | 'retail' | 'return'>('retail');

  // Fetch vegetables & customers on mount
  useEffect(() => {
    const fetchFilterMeta = async () => {
      try {
        const [purchaseMetaRes, salesMetaRes] = await Promise.all([
          jwtAxios.get(ENDPOINTS.PURCHASE_META),
          jwtAxios.get(ENDPOINTS.SALES_META),
        ]);
        setVegetables(purchaseMetaRes.data?.result?.vegetables || []);
        setCustomers(salesMetaRes.data?.result?.customers || []);
      } catch (err) {
        console.error('Failed to load filter metadata', err);
      }
    };
    fetchFilterMeta();
  }, []);

  // Fetch wholesale spoils
  const fetchSpoils = async () => {
    setSpoilsLoading(true);
    try {
      let url = ENDPOINTS.STOCK_SPOILAGE + '?';
      if (selectedVeg) url += `vegetableId=${selectedVeg}&`;
      if (spoilsDateRange) {
        url += `from=${spoilsDateRange[0].format('YYYY-MM-DD')}&to=${spoilsDateRange[1].format('YYYY-MM-DD')}`;
      }
      const res = await jwtAxios.get(url);
      setSpoilsData(res.data?.result || []);
    } catch (err) {
      message.error('Failed to load wholesale spoils history');
    } finally {
      setSpoilsLoading(false);
    }
  };

  // Fetch retail spoils
  const fetchRetailSpoils = async () => {
    setRetailSpoilsLoading(true);
    try {
      let url = ENDPOINTS.RETAIL_STOCK_SPOILAGE + '?';
      if (selectedRetailVeg) url += `vegetableId=${selectedRetailVeg}&`;
      if (retailSpoilsDateRange) {
        url += `from=${retailSpoilsDateRange[0].format('YYYY-MM-DD')}&to=${retailSpoilsDateRange[1].format('YYYY-MM-DD')}`;
      }
      const res = await jwtAxios.get(url);
      const data = res.data?.result?.data || res.data?.result || [];
      setRetailSpoilsData(data);
    } catch (err) {
      message.error('Failed to load retail spoils history');
    } finally {
      setRetailSpoilsLoading(false);
    }
  };

  // Fetch returns
  const fetchReturns = async () => {
    setReturnsLoading(true);
    try {
      let url = ENDPOINTS.STOCK_RETURNS + '?';
      if (selectedCustomer) {
        if (selectedCustomer === 'walkin') {
          url += 'isWalkIn=true&';
        } else {
          url += `customerId=${selectedCustomer}&`;
        }
      }
      if (returnsDateRange) {
        url += `from=${returnsDateRange[0].format('YYYY-MM-DD')}&to=${returnsDateRange[1].format('YYYY-MM-DD')}`;
      }
      const res = await jwtAxios.get(url);
      setReturnsData(res.data?.result || []);
    } catch (err) {
      message.error('Failed to load returns history');
    } finally {
      setReturnsLoading(false);
    }
  };

  useEffect(() => {
    if (activeTab === 'spoils') {
      fetchSpoils();
    } else if (activeTab === 'retailSpoils') {
      fetchRetailSpoils();
    } else {
      fetchReturns();
    }
  }, [activeTab, selectedVeg, spoilsDateRange, selectedRetailVeg, retailSpoilsDateRange, selectedCustomer, returnsDateRange]);

  const handleOpenView = (record: any, type: 'wholesale' | 'retail' | 'return') => {
    setViewRecord(record);
    setViewType(type);
    setViewOpen(true);
  };

  const spoilsColumns = [
    {
      title: 'Date',
      dataIndex: 'spoilageDate',
      render: (date: string) => dayjs(date).format('DD MMM YYYY'),
    },
    {
      title: 'Vegetable',
      dataIndex: ['purchase', 'vegetable', 'name'],
    },
    {
      title: 'Lot No',
      dataIndex: ['purchase', 'lotNo'],
      render: (lot: string) => <Tag color="blue">{lot || '-'}</Tag>,
    },
    {
      title: 'Quantity',
      dataIndex: 'quantity',
      render: (qty: string, record: any) => {
        const saleUnit = record.purchase?.unit || 'KG';
        const isBagOnly = saleUnit !== 'KG' && Number(record.purchase?.quantity || 0) === 0;
        const unitLabel = isBagOnly ? (saleUnit === 'BOX' ? 'BOX' : 'BAG') : 'KG';
        
        return <Tag color="red">{Number(qty)} {unitLabel}</Tag>;
      },
    },
    {
      title: 'Reason',
      dataIndex: 'reason',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: 'Remarks',
      dataIndex: 'remarks',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: 'Actions',
      width: 80,
      render: (_: any, record: any) => (
        <Popover content="View Details">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleOpenView(record, 'wholesale')}
          />
        </Popover>
      ),
    },
  ];

  const retailSpoilsColumns = [
    {
      title: 'Date',
      dataIndex: 'spoilageDate',
      render: (date: string) => dayjs(date).format('DD MMM YYYY'),
    },
    {
      title: 'Vegetable',
      render: (_: any, record: any) => record.retailStock?.purchase?.vegetable?.name || '-',
    },
    {
      title: 'Retail Lot No',
      render: (_: any, record: any) => <Tag color="volcano">{record.retailStock?.lotNo || '-'}</Tag>,
    },
    {
      title: 'Spoiled Qty',
      dataIndex: 'quantity',
      render: (qty: string) => (
        <Tag color="volcano" className="font-bold">{Number(qty)} KG</Tag>
      ),
    },
    {
      title: 'Reason',
      dataIndex: 'reason',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: 'Remarks',
      dataIndex: 'remarks',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: 'Actions',
      width: 80,
      render: (_: any, record: any) => (
        <Popover content="View Full Details">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleOpenView(record, 'retail')}
          />
        </Popover>
      ),
    },
  ];

  const returnsColumns = [
    {
      title: 'Return Date',
      dataIndex: 'returnDate',
      render: (date: string) => dayjs(date).format('DD MMM YYYY'),
    },
    {
      title: 'Invoice No',
      dataIndex: ['saleItem', 'sale', 'invoiceNo'],
    },
    {
      title: 'Customer',
      key: 'customer',
      render: (_: any, record: any) => {
        const sale = record.saleItem?.sale;
        if (sale?.customer?.name) return sale.customer.name;
        if (sale?.walkInName) return `${sale.walkInName} (Walk-in)`;
        return 'Walk-in Customer';
      },
    },
    {
      title: 'Vegetable',
      dataIndex: ['purchase', 'vegetable', 'name'],
    },
    {
      title: 'Return Qty',
      dataIndex: 'quantity',
      render: (qty: string, record: any) => {
        const saleUnit = record.saleItem?.saleUnit || record.purchase?.unit || 'KG';
        const isBagOnly = saleUnit !== 'KG' && Number(record.saleItem?.quantity || 0) === 0;
        const unitLabel = isBagOnly ? (saleUnit === 'BOX' ? 'BOX' : 'BAG') : 'KG';
        
        return <Tag color="orange">{Number(qty)} {unitLabel}</Tag>;
      },
    },
    {
      title: 'Return Amount',
      dataIndex: 'returnAmount',
      render: (amt: string) => `₹${Number(amt).toFixed(2)}`,
    },
    {
      title: 'Reason',
      dataIndex: 'reason',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: 'Actions',
      width: 80,
      render: (_: any, record: any) => (
        <Popover content="View Details">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleOpenView(record, 'return')}
          />
        </Popover>
      ),
    },
  ];

  return (
    <AppContainer title="Spoils & Returns History">
      <Tabs
        activeKey={activeTab}
        onChange={(key) => setActiveTab(key)}
        items={[
          {
            key: 'spoils',
            label: 'Wholesale Stock Spoilage',
            children: (
              <div>
                <div className="mb-4 flex gap-4">
                  <Select
                    placeholder="Filter by Vegetable"
                    allowClear
                    style={{ width: 220 }}
                    options={vegetables.map(v => ({ label: v.name, value: v.id }))}
                    onChange={(val) => setSelectedVeg(val)}
                  />
                  <RangePicker onChange={(dates) => setSpoilsDateRange(dates)} />
                  <Button onClick={fetchSpoils}>Refresh</Button>
                </div>
                <Table
                  rowKey="id"
                  columns={spoilsColumns}
                  dataSource={spoilsData}
                  loading={spoilsLoading}
                  pagination={{ pageSize: 15 }}
                />
              </div>
            ),
          },
          {
            key: 'retailSpoils',
            label: 'Retail Stock Spoilage',
            children: (
              <div>
                <div className="mb-4 flex gap-4">
                  <Select
                    placeholder="Filter by Vegetable"
                    allowClear
                    style={{ width: 220 }}
                    options={vegetables.map(v => ({ label: v.name, value: v.id }))}
                    onChange={(val) => setSelectedRetailVeg(val)}
                  />
                  <RangePicker onChange={(dates) => setRetailSpoilsDateRange(dates)} />
                  <Button onClick={fetchRetailSpoils}>Refresh</Button>
                </div>
                <Table
                  rowKey="id"
                  columns={retailSpoilsColumns}
                  dataSource={retailSpoilsData}
                  loading={retailSpoilsLoading}
                  pagination={{ pageSize: 15 }}
                />
              </div>
            ),
          },
          {
            key: 'returns',
            label: 'Sale Returns History',
            children: (
              <div>
                <div className="mb-4 flex gap-4">
                  <Select
                    placeholder="Filter by Customer"
                    allowClear
                    showSearch
                    optionFilterProp="label"
                    filterOption={(input, option) =>
                      (option?.label as string)
                        ?.toLowerCase()
                        .includes(input.toLowerCase())
                    }
                    style={{ width: 250 }}
                    value={selectedCustomer}
                    options={[
                      { label: 'Walk-in / Counter Sales', value: 'walkin' },
                      ...customers.map(c => ({ label: c.name, value: String(c.id) })),
                    ]}
                    onChange={(val) => setSelectedCustomer(val)}
                  />
                  <RangePicker onChange={(dates) => setReturnsDateRange(dates)} />
                  <Button onClick={fetchReturns}>Refresh</Button>
                </div>
                <Table
                  rowKey="id"
                  columns={returnsColumns}
                  dataSource={returnsData}
                  loading={returnsLoading}
                  pagination={{ pageSize: 15 }}
                />
              </div>
            ),
          },
        ]}
      />

      {/* Details Modal */}
      <Modal
        title={
          viewType === 'retail'
            ? 'Retail Stock Spoilage Details'
            : viewType === 'wholesale'
            ? 'Wholesale Stock Spoilage Details'
            : 'Sale Return Details'
        }
        open={viewOpen}
        onCancel={() => {
          setViewOpen(false);
          setViewRecord(null);
        }}
        footer={<Button onClick={() => setViewOpen(false)}>Close</Button>}
        width={600}
      >
        {viewRecord && (
          <Descriptions column={1} bordered size="small" className="mt-2">
            <Descriptions.Item label="Date">
              {dayjs(viewRecord.spoilageDate || viewRecord.returnDate).format('DD MMMM YYYY')}
            </Descriptions.Item>

            {viewType === 'retail' && (
              <>
                <Descriptions.Item label="Retail Lot No">
                  <Tag color="volcano">{viewRecord.retailStock?.lotNo || '-'}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Vegetable">
                  {viewRecord.retailStock?.purchase?.vegetable?.name || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Spoiled Quantity">
                  <Tag color="red" className="font-bold">{Number(viewRecord.quantity)} KG</Tag>
                </Descriptions.Item>
              </>
            )}

            {viewType === 'wholesale' && (
              <>
                <Descriptions.Item label="Wholesale Lot No">
                  <Tag color="blue">{viewRecord.purchase?.lotNo || '-'}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Vegetable">
                  {viewRecord.purchase?.vegetable?.name || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Spoiled Quantity">
                  <Tag color="red" className="font-bold">{Number(viewRecord.quantity)} KG</Tag>
                </Descriptions.Item>
              </>
            )}

            {viewType === 'return' && (
              <>
                <Descriptions.Item label="Invoice No">
                  {viewRecord.saleItem?.sale?.invoiceNo || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Customer">
                  {viewRecord.saleItem?.sale?.customer?.name ||
                    (viewRecord.saleItem?.sale?.walkInName
                      ? `${viewRecord.saleItem?.sale?.walkInName} (Walk-in)`
                      : 'Walk-in Customer')}
                </Descriptions.Item>
                {viewRecord.saleItem?.sale?.walkInMobile && (
                  <Descriptions.Item label="Customer Mobile">
                    {viewRecord.saleItem?.sale?.walkInMobile}
                  </Descriptions.Item>
                )}
                <Descriptions.Item label="Vegetable">
                  {viewRecord.purchase?.vegetable?.name || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="Return Quantity">
                  <Tag color="orange" className="font-bold">{Number(viewRecord.quantity)} KG</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Return Amount">
                  ₹{Number(viewRecord.returnAmount || 0).toFixed(2)}
                </Descriptions.Item>
              </>
            )}

            <Descriptions.Item label="Reason">
              {viewRecord.reason || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="Remarks">
              <span className="whitespace-pre-wrap">{viewRecord.remarks || '-'}</span>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </AppContainer>
  );
}
