import { useEffect, useState } from 'react';
import {
  DatePicker,
  Input,
  Select,
  Space,
  Spin,
  Table,
  message,
  Tag,
  Button,
  Row,
  Col,
} from 'antd';
import { DownloadOutlined, FilePdfOutlined, RedoOutlined } from '@ant-design/icons';
import dayjs, { Dayjs } from 'dayjs';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';
import SummaryCard from '../../components/SummaryCard';

const ENTITY_LABEL = 'Arrivals Report';

interface NamedOption {
  id: string;
  name: string;
}

const { RangePicker } = DatePicker;

const SETTLEMENT_STATUS_OPTIONS = [
  { label: 'All', value: 'ALL' },
  { label: 'Unsettled', value: 'UNSETTLED' },
  { label: 'Partially Settled', value: 'PARTIALLY_SETTLED' },
  { label: 'Settled', value: 'SETTLED' },
];

const statusTagColor: Record<string, string> = {
  SETTLED: 'green',
  PARTIALLY_SETTLED: 'gold',
  UNSETTLED: 'red',
};

const statusLabel: Record<string, string> = {
  SETTLED: 'Settled',
  PARTIALLY_SETTLED: 'Partial',
  UNSETTLED: 'Unsettled',
};

const ArrivalReport = () => {
  const [searchText, setSearchText] = useState('');
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs] | null>(null);
  const [supplierId, setSupplierId] = useState<string | undefined>(undefined);
  const [vegetableId, setVegetableId] = useState<string | undefined>(undefined);
  const [settlementStatus, setSettlementStatus] = useState<string | undefined>(undefined);

  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [exportLoading, setExportLoading] = useState(false);
  const [exportPdfLoading, setExportPdfLoading] = useState(false);

  const [suppliers, setSuppliers] = useState<NamedOption[]>([]);
  const [vegetables, setVegetables] = useState<NamedOption[]>([]);

  const [summary, setSummary] = useState({
    totalArrivals: 0,
    totalQtyKg: 0,
    totalRemainingKg: 0,
    totalFreight: 0,
  });

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: Number(import.meta.env.VITE_PAGE_SIZE) || 10,
    total: 0,
    totalPages: 0,
  });

  // Fetch filter meta (suppliers & vegetables) once on mount
  const fetchMeta = async () => {
    try {
      const res = await jwtAxios.get(ENDPOINTS.PURCHASE_META);
      const result = res.data?.result || {};
      setSuppliers(result.suppliers || []);
      setVegetables(result.vegetables || []);
    } catch {
      setSuppliers([]);
      setVegetables([]);
    }
  };

  const buildParams = (
    page: number,
    limit: number,
    search: string,
    range: [Dayjs, Dayjs] | null,
    supplier: string | undefined,
    vegetable: string | undefined,
    status: string | undefined
  ) => {
    const params = new URLSearchParams();
    params.set('page', String(page));
    params.set('limit', String(limit));
    if (search) params.set('search', search);
    if (range) {
      params.set('dateFrom', range[0].format('YYYY-MM-DD'));
      params.set('dateTo', range[1].format('YYYY-MM-DD'));
    }
    if (supplier) params.set('supplierId', supplier);
    if (vegetable) params.set('vegetableId', vegetable);
    if (status && status !== 'ALL') params.set('settlementStatus', status);
    return params;
  };

  const fetchData = async (
    page = pagination.current,
    limit = pagination.pageSize,
    search = searchText,
    range: [Dayjs, Dayjs] | null = dateRange,
    supplier = supplierId,
    vegetable = vegetableId,
    status = settlementStatus
  ) => {
    setLoading(true);
    try {
      const params = buildParams(page, limit, search, range, supplier, vegetable, status);
      const res = await jwtAxios.get(`${ENDPOINTS.ARRIVALS_REPORT}?${params.toString()}`);
      const records: any[] = res.data?.result?.data || [];
      const metaInfo = res.data?.result?.meta || {};

      setData(records.map((r) => ({ ...r, key: r.id })));
      setPagination((prev) => ({
        ...prev,
        current: metaInfo.page ?? page,
        pageSize: metaInfo.limit ?? limit,
        total: metaInfo.total ?? prev.total,
        totalPages: metaInfo.totalPages ?? prev.totalPages,
      }));

      // Compute page-level summaries
      const totalArrivals = records.length;
      const totalQtyKg = records.reduce((s, r) => s + Number(r.quantity ?? 0), 0);
      const totalRemainingKg = records.reduce((s, r) => s + Number(r.remainingQuantity ?? 0), 0);
      const totalFreight = records.reduce((s, r) => s + Number(r.totalFreight ?? r.freight ?? 0), 0);
      setSummary({ totalArrivals, totalQtyKg, totalRemainingKg, totalFreight });
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to fetch arrivals report');
      setData([]);
    } finally {
      setLoading(false);
    }
  };

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

  // ── Export Excel ──────────────────────────────────────────────────
  const handleExportExcel = async () => {
    if (!data.length) { message.warning('No data to export'); return; }
    setExportLoading(true);
    try {
      const params = buildParams(1, 9999, searchText, dateRange, supplierId, vegetableId, settlementStatus);
      const response = await jwtAxios.get(`${ENDPOINTS.ARRIVALS_REPORT_EXPORT}?${params.toString()}`, { responseType: 'blob' });
      const disposition = response.headers['content-disposition'];
      let fileName = `arrivals-report-${dayjs().format('YYYY-MM-DD')}.xlsx`;
      if (disposition) {
        const match = disposition.match(/filename\*?=(?:UTF-8'')?\"?([^"\n;]+)\"?/i);
        if (match?.[1]) fileName = decodeURIComponent(match[1]);
      }
      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url; a.download = fileName;
      document.body.appendChild(a); a.click();
      document.body.removeChild(a); window.URL.revokeObjectURL(url);
      message.success('Excel exported successfully');
    } catch { message.error('Failed to export Excel'); }
    finally { setExportLoading(false); }
  };

  // ── Export PDF ────────────────────────────────────────────────────
  const handleExportPdf = async () => {
    if (!data.length) { message.warning('No data to export'); return; }
    setExportPdfLoading(true);
    try {
      const params = buildParams(1, 9999, searchText, dateRange, supplierId, vegetableId, settlementStatus);
      const response = await jwtAxios.get(`${ENDPOINTS.ARRIVALS_REPORT_EXPORT_PDF}?${params.toString()}`, { responseType: 'blob' });
      const disposition = response.headers['content-disposition'];
      let fileName = `arrivals-report-${dayjs().format('YYYY-MM-DD')}.pdf`;
      if (disposition) {
        const match = disposition.match(/filename\*?=(?:UTF-8'')?\"?([^"\n;]+)\"?/i);
        if (match?.[1]) fileName = decodeURIComponent(match[1]);
      }
      const blob = new Blob([response.data], { type: 'application/pdf' });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url; a.download = fileName;
      document.body.appendChild(a); a.click();
      document.body.removeChild(a); window.URL.revokeObjectURL(url);
      message.success('PDF exported successfully');
    } catch { message.error('Failed to export PDF'); }
    finally { setExportPdfLoading(false); }
  };

  // ── Filter handlers ───────────────────────────────────────────────
  const handleSearch = (val: string) => fetchData(1, pagination.pageSize, val, dateRange, supplierId, vegetableId, settlementStatus);
  const handleDateChange = (vals: any) => {
    const range = vals as [Dayjs, Dayjs] | null;
    setDateRange(range);
    fetchData(1, pagination.pageSize, searchText, range, supplierId, vegetableId, settlementStatus);
  };
  const handleSupplierChange = (val: string | undefined) => {
    setSupplierId(val);
    fetchData(1, pagination.pageSize, searchText, dateRange, val, vegetableId, settlementStatus);
  };
  const handleVegetableChange = (val: string | undefined) => {
    setVegetableId(val);
    fetchData(1, pagination.pageSize, searchText, dateRange, supplierId, val, settlementStatus);
  };
  const handleStatusChange = (val: string | undefined) => {
    setSettlementStatus(val);
    fetchData(1, pagination.pageSize, searchText, dateRange, supplierId, vegetableId, val);
  };
  const handleReset = () => {
    setSearchText(''); setDateRange(null);
    setSupplierId(undefined); setVegetableId(undefined); setSettlementStatus(undefined);
    fetchData(1, pagination.pageSize, '', null, undefined, undefined, undefined);
  };

  // ── Table columns ─────────────────────────────────────────────────
  const columns = [
    {
      title: 'S.No',
      render: (_: any, __: any, index: number) => (pagination.current - 1) * pagination.pageSize + index + 1,
      width: 60,
    },
    {
      title: 'Date',
      dataIndex: 'arrivalDate',
      render: (v: any, r: any) => {
        const d = v ?? r.purchaseDate;
        return d ? dayjs(d).format('DD/MM/YYYY') : '-';
      },
      width: 100,
    },
    {
      title: 'Lot No',
      dataIndex: 'lotNo',
      width: 100,
    },
    {
      title: 'Bill No',
      dataIndex: 'billNo',
      render: (v: any) => v || '-',
      width: 100,
    },
    {
      title: 'Truck No',
      dataIndex: 'truckNo',
      render: (v: any) => v || '-',
      width: 100,
    },
    {
      title: 'Supplier / Farmer',
      dataIndex: 'supplier',
      render: (s: any, r: any) => s?.name ?? r.cashSupplierName ?? r.agentName ?? '-',
      width: 160,
    },
    {
      title: 'Vegetable',
      dataIndex: 'vegetable',
      render: (v: any) => v?.name ?? '-',
      width: 120,
    },
    {
      title: 'Qty (KG)',
      dataIndex: 'quantity',
      render: (v: any) => <Tag color="purple">{Number(v ?? 0).toFixed(2)}</Tag>,
      align: 'right' as const,
      width: 100,
    },
    {
      title: 'Bags',
      dataIndex: 'bags',
      render: (v: any, r: any) => {
        const n = Number(v ?? 0);
        return n > 0 ? <Tag color="blue">{n} {r.unit}</Tag> : <Tag color="default">-</Tag>;
      },
      width: 90,
    },
    {
      title: 'Rem. Qty',
      dataIndex: 'remainingQuantity',
      render: (v: any, r: any) => {
        const rem = Number(v ?? 0);
        const total = Number(r.quantity ?? 0);
        const color = rem === 0 ? 'red' : rem <= total * 0.2 ? 'orange' : 'green';
        return <Tag color={color}>{rem.toFixed(2)} KG</Tag>;
      },
      align: 'right' as const,
      width: 110,
    },
    {
      title: 'Freight (₹)',
      dataIndex: 'totalFreight',
      render: (v: any, r: any) => `₹${Number(v ?? r.freight ?? 0).toFixed(2)}`,
      align: 'right' as const,
      width: 110,
    },
    {
      title: 'Advance (₹)',
      dataIndex: 'advanceAmount',
      render: (v: any) => `₹${Number(v ?? 0).toFixed(2)}`,
      align: 'right' as const,
      width: 110,
    },
    {
      title: 'Settlement',
      dataIndex: 'arrivalSettlement',
      render: (s: any) => {
        const status = s?.status ?? 'UNSETTLED';
        return <Tag color={statusTagColor[status]}>{statusLabel[status] ?? status}</Tag>;
      },
      width: 120,
    },
  ];

  return (
    <div>
      <Spin spinning={loading}>
        <AppContainer
          title={ENTITY_LABEL}
          headerAction={
            <Space wrap>
              <Button
                icon={<DownloadOutlined />}
                style={{ color: '#52c41a', borderColor: '#52c41a' }}
                loading={exportLoading}
                onClick={handleExportExcel}
              >
                Export Excel
              </Button>
              <Button
                icon={<FilePdfOutlined />}
                danger
                loading={exportPdfLoading}
                onClick={handleExportPdf}
              >
                Export PDF
              </Button>
            </Space>
          }
        >
          {/* Summary Cards */}
          <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
            <Col xs={24} sm={12} md={6}>
              <SummaryCard
                label="Total Arrivals"
                value={summary.totalArrivals}
                color="#1677ff"
                icon={<span style={{ fontSize: 20 }}>🚛</span>}
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <SummaryCard
                label="Total Qty (KG)"
                value={summary.totalQtyKg}
                color="#722ed1"
                icon={<span style={{ fontSize: 20 }}>⚖️</span>}
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <SummaryCard
                label="Remaining Qty (KG)"
                value={summary.totalRemainingKg}
                color="#fa8c16"
                icon={<span style={{ fontSize: 20 }}>📦</span>}
              />
            </Col>
            <Col xs={24} sm={12} md={6}>
              <SummaryCard
                label="Total Freight (₹)"
                value={summary.totalFreight}
                color="#f5222d"
                icon={<span style={{ fontSize: 20 }}>🚚</span>}
              />
            </Col>
          </Row>

          {/* Filters */}
          <div className="flex justify-between items-center mb-4 pb-4 border-b border-gray-200">
            <Space wrap>
              <RangePicker value={dateRange as any} onChange={handleDateChange} />
              <Select
                allowClear showSearch placeholder="Filter by supplier"
                style={{ width: 200 }} value={supplierId}
                onChange={handleSupplierChange} optionFilterProp="label"
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
                options={suppliers.map((s) => ({ label: s.name, value: s.id }))}
              />
              <Select
                allowClear showSearch placeholder="Filter by vegetable"
                style={{ width: 200 }} value={vegetableId}
                onChange={handleVegetableChange} optionFilterProp="label"
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
                options={vegetables.map((v) => ({ label: v.name, value: v.id }))}
              />
              <Select
                allowClear placeholder="Settlement status"
                style={{ width: 180 }} value={settlementStatus}
                onChange={handleStatusChange}
                options={SETTLEMENT_STATUS_OPTIONS}
              />
              <Input.Search
                placeholder="Search lot, supplier…"
                value={searchText}
                onChange={(e) => {
                  setSearchText(e.target.value);
                  if (!e.target.value) handleSearch('');
                }}
                onSearch={handleSearch}
                allowClear style={{ width: 200 }}
              />
              <Button icon={<RedoOutlined />} onClick={handleReset}>Reset</Button>
            </Space>
          </div>

          {/* Table */}
          <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, dateRange, supplierId, vegetableId, settlementStatus)
            }
          />
          <div className="text-center mt-2">
            <Tag color="cyan">Page {pagination.current} of {pagination.totalPages}</Tag>
          </div>
        </AppContainer>
      </Spin>
    </div>
  );
};

export default ArrivalReport;
