import React, { useEffect, useState, useCallback, useMemo } from 'react';
import {
  Button,
  Input,
  message,
  Spin,
  Table,
  Tag,
  Typography,
  Space,
  Select,
  Row,
  Col,
} from 'antd';
import type { TableColumnsType, TablePaginationConfig } from 'antd';
import {
  FileExcelOutlined,
  FilePdfOutlined,
} from '@ant-design/icons';
import { AppContainer } from '../../components/AppContainer';
import jwtAxios from '../../api/axiosInstance';
import { ENDPOINTS } from '../../api/endpoints';
import SummaryCard from '../../components/SummaryCard';

const { Text } = Typography;

// ─────────────────────────────────────────────────────────────
//  Data Structures
// ─────────────────────────────────────────────────────────────

export interface OutstandingParty {
  id: string;
  name: string;
  tamilName: string | null;
  mobileNo: string;
  address: string | null;
  openingBalance: number;
  outstandingBalance: number;
  status: boolean;
}

export interface OutstandingSummary {
  totalCount: number;
  withBalanceCount: number;
  totalOutstandingAmount: number;
  clearedCount: number;
}

export interface OutstandingApiResponse {
  data: OutstandingParty[];
  summary: OutstandingSummary;
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
}

// ─────────────────────────────────────────────────────────────
//  Helpers
// ─────────────────────────────────────────────────────────────

const fmt = (val?: number | null): string => {
  const n = Number(val ?? 0);
  return isNaN(n) ? '0.00' : n.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
};

const emptySummary: OutstandingSummary = {
  totalCount: 0,
  withBalanceCount: 0,
  totalOutstandingAmount: 0,
  clearedCount: 0,
};

// ─────────────────────────────────────────────────────────────
//  Column builder
// ─────────────────────────────────────────────────────────────

function buildColumns(): TableColumnsType<OutstandingParty> {
  return [
    {
      title: '#',
      key: 'sno',
      width: 55,
      fixed: 'left',
      render: (_: unknown, __: OutstandingParty, index: number) => (
        <Text className="text-slate-400 text-xs">{index + 1}</Text>
      ),
    },
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      fixed: 'left',
      width: 200,
      render: (name: string, record: OutstandingParty) => (
        <div>
          <div className="font-semibold text-slate-800 text-sm">{name}</div>
          {record.tamilName && (
            <div className="text-xs text-slate-400 mt-0.5">{record.tamilName}</div>
          )}
        </div>
      ),
    },
    {
      title: 'Mobile',
      dataIndex: 'mobileNo',
      key: 'mobileNo',
      width: 130,
      render: (mob: string) => (
        <Text className="font-mono text-slate-600 text-sm">{mob || '—'}</Text>
      ),
    },
    {
      title: 'Outstanding Balance',
      dataIndex: 'outstandingBalance',
      key: 'outstandingBalance',
      align: 'right' as const,
      width: 180,
      render: (val: number) => {
        const n = Number(val);
        if (n <= 0) {
          return (
            <Tag color="success" className="font-semibold">
              Cleared
            </Tag>
          );
        }
        return <span className="font-bold text-red-600 text-sm">₹{fmt(n)}</span>;
      },
    },
  ];
}

// ─────────────────────────────────────────────────────────────
//  Main Page
// ─────────────────────────────────────────────────────────────

const OutstandingReport: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'customers' | 'suppliers'>('customers');
  const [data, setData] = useState<OutstandingParty[]>([]);
  const [summary, setSummary] = useState<OutstandingSummary>(emptySummary);
  const [loading, setLoading] = useState<boolean>(false);
  const [search, setSearch] = useState<string>('');
  
  const [pagination, setPagination] = useState<TablePaginationConfig & { totalPages?: number }>({
    current: 1,
    pageSize: 20,
    total: 0,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20', '50', '100'],
  });

  const [exportPdfLoading, setExportPdfLoading] = useState<boolean>(false);
  const [exportExcelLoading, setExportExcelLoading] = useState<boolean>(false);

  const fetchReport = useCallback(async (page: number, limit: number, query: string, type: 'customers' | 'suppliers') => {
    setLoading(true);
    try {
      const res = await jwtAxios.get<any, { data: { data: OutstandingApiResponse } }>(ENDPOINTS.OUTSTANDING_REPORT, {
        params: {
          type,
          page,
          limit,
          search: query,
        }
      });

      const payload = res.data.data;
      setData(payload.data);
      setSummary(payload.summary);
      setPagination(prev => ({
          ...prev, 
          current: payload.meta.page, 
          pageSize: payload.meta.limit, 
          total: payload.meta.total,
          totalPages: payload.meta.totalPages
      }));
    } catch (err: any) {
      message.error(err.response?.data?.message || `Failed to fetch outstanding report`);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchReport(pagination.current || 1, pagination.pageSize || 20, search, activeTab);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [activeTab]); // Trigger on tab change only

  const handleSearch = (value: string) => {
    setSearch(value);
    fetchReport(1, pagination.pageSize || 20, value, activeTab);
  };

  const handleTableChange = (pag: TablePaginationConfig) => {
    fetchReport(pag.current || 1, pag.pageSize || 20, search, activeTab);
  };

  const columns = useMemo(() => buildColumns(), []);

  // ── Exports ───────────────────────────────────────────────
  const handleExportPdf = async () => {
    setExportPdfLoading(true);
    try {
      const res = await jwtAxios.get(
        `${ENDPOINTS.OUTSTANDING_REPORT_EXPORT_PDF}?type=${activeTab}`,
        { responseType: 'blob' }
      );
      const blob = new Blob([res.data], { type: 'application/pdf' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${activeTab}-outstanding-report.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      message.success('PDF downloaded successfully');
    } catch {
      message.error('Failed to export PDF');
    } finally {
      setExportPdfLoading(false);
    }
  };

  const handleExportExcel = async () => {
    setExportExcelLoading(true);
    try {
      const res = await jwtAxios.get(
        `${ENDPOINTS.OUTSTANDING_REPORT_EXPORT_EXCEL}?type=${activeTab}`,
        { responseType: 'blob' }
      );
      const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `${activeTab}-outstanding-report.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      message.success('Excel downloaded successfully');
    } catch {
      message.error('Failed to export Excel');
    } finally {
      setExportExcelLoading(false);
    }
  };

  // ── Render ────────────────────────────────────────────────
  return (
    <div>
      <Spin spinning={loading}>
        <AppContainer
          title="Outstanding Report"
          headerAction={
            <Space>
              <Button
                icon={<FilePdfOutlined />}
                danger
                loading={exportPdfLoading}
                onClick={handleExportPdf}
              >
                Export PDF
              </Button>
              <Button
                icon={<FileExcelOutlined />}
                style={{ color: '#52c41a', borderColor: '#52c41a' }}
                loading={exportExcelLoading}
                onClick={handleExportExcel}
              >
                Export Excel
              </Button>
            </Space>
          }
        >
          {/* Summary Cards */}
          <Row gutter={[16, 16]} style={{ marginBottom: 20 }}>
            <Col xs={24} md={6}>
              <SummaryCard
                label="Total Parties"
                value={summary.totalCount}
                color="#1677ff"
                showCurrency={false}
                icon={<span style={{ fontSize: 20 }}>👥</span>}
              />
            </Col>
            <Col xs={24} md={6}>
              <SummaryCard
                label="With Balance"
                value={summary.withBalanceCount}
                color="#f5222d"
                showCurrency={false}
                icon={<span style={{ fontSize: 20 }}>⚠️</span>}
              />
            </Col>
            <Col xs={24} md={6}>
              <SummaryCard
                label="Cleared"
                value={summary.clearedCount}
                color="#52c41a"
                showCurrency={false}
                icon={<span style={{ fontSize: 20 }}>✅</span>}
              />
            </Col>
            <Col xs={24} md={6}>
              <SummaryCard
                label="Total Outstanding"
                value={summary.totalOutstandingAmount}
                color="#faad14"
                icon={<span style={{ fontSize: 20 }}>💰</span>}
              />
            </Col>
          </Row>

          {/* Search boxes and Table */}
          <div className="flex justify-between items-center mb-4 pb-4 border-b border-gray-200">
            <Space>
              <Select
                value={activeTab}
                onChange={(val) => setActiveTab(val)}
                options={[
                  { label: 'Customer Outstanding', value: 'customers' },
                  { label: 'Supplier Outstanding', value: 'suppliers' },
                ]}
                style={{ width: 220 }}
              />
              <Input.Search
                placeholder="Search by name or mobile..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                onSearch={handleSearch}
                allowClear
                style={{ width: 260 }}
              />
            </Space>
          </div>

          <Table<OutstandingParty>
            rowKey="id"
            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={handleTableChange}
            rowClassName={(record) =>
              Number(record.outstandingBalance) > 0
                ? 'bg-red-50/30 hover:bg-red-50'
                : 'hover:bg-green-50/30'
            }
          />
          <div className="text-center mt-2">
            <Tag color="cyan">
              Page {pagination.current} of {pagination.totalPages || 1}
            </Tag>
          </div>
        </AppContainer>
      </Spin>
    </div>
  );
};

export default OutstandingReport;
