import { useEffect, useState } from 'react';
import {
  Input,
  Space,
  Spin,
  Table,
  Tag,
  message,
  Button,
  DatePicker,
} from 'antd';
import {

  ShoppingCartOutlined,
  DollarOutlined,
  RiseOutlined,
  FallOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import SummaryCard from '../../components/SummaryCard';
import dayjs from 'dayjs';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';

export const AllSales = () => {
  const [searchText, setSearchText] = useState('');
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [exportLoading, setExportLoading] = useState<boolean>(false);
  const [filterDate, setFilterDate] = useState<[dayjs.Dayjs | null, dayjs.Dayjs | null]>([null, null]);
  const [summary, setSummary] = useState({
    totalPurchase: 0,
    totalSales: 0,
    totalProfit: 0,
  });
  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,
    dates: [dayjs.Dayjs | null, dayjs.Dayjs | null] = filterDate
  ) => {
    setLoading(true);
    try {
      let url = `${ENDPOINTS.ALL_SALES}?page=${page}&limit=${limit}`;
      if (search) url += `&search=${encodeURIComponent(search)}`;
      if (dates && dates[0] && dates[1]) {
        url += `&dateFrom=${dates[0].format('YYYY-MM-DD')}&dateTo=${dates[1].format('YYYY-MM-DD')}`;
      }

      const res = await jwtAxios.get(url);
      const records = res.data?.result?.data || [];
      const meta = res.data?.result?.meta || {};
      const summaryData = res.data?.result?.summary || {
        totalPurchase: 0,
        totalSales: 0,
        totalProfit: 0,
      };

      setSummary(summaryData);
      setData(records.map((r: any) => ({ key: `${r.source}-${r.id}`, ...r })));
      setPagination((prev) => ({
        ...prev,
        current: meta.page ?? page,
        pageSize: meta.limit ?? limit,
        total: meta.total ?? prev.total,
        totalPages: meta.totalPages ?? prev.totalPages,
      }));
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to fetch all sales');
    } finally {
      setLoading(false);
    }
  };

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

  const handleExport = async () => {
    setExportLoading(true);
    try {
      const params = new URLSearchParams();
      if (searchText) params.set('search', searchText);
      if (filterDate && filterDate[0] && filterDate[1]) {
        params.set('dateFrom', filterDate[0].format('YYYY-MM-DD'));
        params.set('dateTo', filterDate[1].format('YYYY-MM-DD'));
      }

      const url = `${ENDPOINTS.ALL_SALES_EXPORT_PDF}${params.toString() ? '?' + params.toString() : ''}`;
      const response = await jwtAxios.get(url, { responseType: 'blob' });

      const disposition = response.headers['content-disposition'];
      let fileName = `all-sales-${dayjs().format('YYYY-MM-DD')}.pdf`;
      if (disposition) {
          const match = disposition.match(/filename="?([^"\n;]+)"?/i);
          if (match?.[1]) fileName = match[1];
      }

      const blob = new Blob([response.data], { type: 'application/pdf' });
      const objectUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = objectUrl;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(objectUrl);
      
      message.success('PDF exported successfully');
    } catch (err: any) {
      message.error(err.response?.data?.message || 'Failed to export sales PDF');
    } finally {
      setExportLoading(false);
    }
  };

  const columns = [
    {
      title: 'S.No',
      render: (_: any, __: any, index: number) =>
        (pagination.current - 1) * pagination.pageSize + index + 1,
      width: 60,
    },
    {
      title: 'Invoice No',
      dataIndex: 'invoiceNo',
      render: (text: string) => <Tag color="blue">{text}</Tag>,
    },
    {
      title: 'Sale Date',
      dataIndex: 'invoiceDate',
      render: (date: string) => (date ? dayjs(date).format('DD MMM YYYY') : '-'),
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      render: (val: string) => val || 'Walk-in Customer',
    },
    {
      title: 'Items',
      dataIndex: 'itemCount',
      render: (val: number) => (
        <span>
          {val} item{val > 1 ? 's' : ''}
        </span>
      ),
    },
    {
      title: 'Actual Cost',
      dataIndex: 'actualCostPrice',
      render: (val: number) => (
        <Tag color="volcano">{'\u20B9'}{(Number(val) || 0).toFixed(2)}</Tag>
      ),
    },
    {
      title: 'Selling Price (Grand Total)',
      dataIndex: 'grandTotal',
      render: (val: number) => <Tag color="green">{'\u20B9'}{Number(val).toFixed(2)}</Tag>,
    },
    {
      title: 'Profit / Loss',
      dataIndex: 'profit',
      render: (val: number) => {
        const profitValue = Number(val) || 0;
        return (
          <Tag color={profitValue >= 0 ? "success" : "error"}>
            {profitValue >= 0 ? '+' : ''}{'\u20B9'}{profitValue.toFixed(2)}
          </Tag>
        );
      },
    },
    {
      title: 'Source',
      dataIndex: 'source',
      render: (val: string) =>
        val === 'wholesale'
          ? <Tag color="purple">Wholesale</Tag>
          : <Tag color="orange">Retail</Tag>,
      filters: [
        { text: 'Wholesale', value: 'wholesale' },
        { text: 'Retail', value: 'retail' },
      ],
      onFilter: (value: any, record: any) => record.source === value,
    },
  ];

  return (
    <div>
      <Spin spinning={loading}>
        <AppContainer
          title="All Sales"
        >
          <div className="flex justify-between items-center mb-4 pb-4 border-b border-gray-200">
            <Space>
              <DatePicker.RangePicker
                value={filterDate as any}
                onChange={(dates) => {
                  setFilterDate(dates as any);
                  fetchData(1, pagination.pageSize, searchText, dates as any);
                }}
                style={{ width: 250 }}
              />
              <Input.Search
                placeholder="Search by Invoice No..."
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                onSearch={(val) => fetchData(1, pagination.pageSize, val, filterDate)}
                allowClear
                style={{ width: 250 }}
              />
              <Button 
                type="primary" 
                icon={<DownloadOutlined />} 
                loading={exportLoading} 
                onClick={handleExport}
              >
                Export PDF
              </Button>
            </Space>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
            <SummaryCard
              label="Total Purchase "
              value={summary.totalPurchase}
              icon={<ShoppingCartOutlined />}
              color="#fa541c"
            />
            <SummaryCard
              label="Total Sales "
              value={summary.totalSales}
              icon={<DollarOutlined />}
              color="#52c41a"
            />
            <SummaryCard
              label="Total Profit "
              value={summary.totalProfit}
              icon={summary.totalProfit >= 0 ? <RiseOutlined /> : <FallOutlined />}
              color={summary.totalProfit >= 0 ? "#52c41a" : "#f5222d"}
            />
          </div>

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

export default AllSales;
