﻿/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable spellcheck/spell-checker */
import React from 'react';
import { Table, Typography, Card, Tooltip, Button } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';
import { FYMonthlyData, MonthData } from '../interface';
import { convertToShorthand } from '@/utills/helper';

const { Title } = Typography;

const TAB_KEY_MAP: Record<string, string> = {
  visits: 'visited',
  tokens: 'token_done',
  bookings: 'booked',
  cancellations: 'dead',
};

interface FYMonthlyTableProps {
  data: FYMonthlyData;
  showBusiness?: boolean;
  filterUserId?: number;
  filterUserRole?: string;
  filterAncestorIds?: number[];
}

interface TableRow extends MonthData {
  key: string;
  isTotal?: boolean;
}

function buildEnquiryUrl(
  metric: keyof typeof TAB_KEY_MAP,
  record: TableRow,
  financialYear: string,
  filterUserId?: number,
  filterUserRole?: string,
  filterAncestorIds?: number[]
): string {
  const fyStartYear = parseInt(financialYear.split('-')[0], 10);
  const year = record.monthNumber >= 4 ? fyStartYear : fyStartYear + 1;
  const monthPadded = String(record.monthNumber).padStart(2, '0');
  const daysInMonth = new Date(year, record.monthNumber, 0).getDate();

  const startDate = `${year}-${monthPadded}-01`;
  const endDate = `${year}-${monthPadded}-${String(daysInMonth).padStart(2, '0')}`;
  const tabKey = TAB_KEY_MAP[metric];

  const params = new URLSearchParams({ tabkey: tabKey, start_date: startDate, end_date: endDate });
  if (filterUserId) params.set('lead_user_id', String(filterUserId));
  if (filterUserRole) params.set('lead_user_role_name', filterUserRole);
  if (filterAncestorIds?.length) params.set('ancestor_ids', filterAncestorIds.join(','));

  return `/enquiries?${params.toString()}`;
}

const FYMonthlyTable: React.FC<FYMonthlyTableProps> = ({
  data,
  showBusiness = true,
  filterUserId,
  filterUserRole,
  filterAncestorIds,
}) => {
  const { months, total, financialYear } = data;

  // Check if business fields exist in data
  const hasBusiness = showBusiness && months.length > 0 && months[0].business !== undefined;

  // Build table data: months + total row
  const tableData: TableRow[] = [
    ...months.map((m) => ({
      ...m,
      key: m.month,
    })),
    {
      key: 'total',
      month: 'Total',
      monthNumber: 0,
      visits: total.visits,
      visitsDuplicate: total.visitsDuplicate,
      visitsRepeatVisit: total.visitsRepeatVisit,
      visitsSumOfMonths: total.visitsSumOfMonths,
      tokens: total.tokens,
      bookings: total.bookings,
      cancellations: total.cancellations,
      netBookings: total.netBookings,
      business: total.business,
      cancelledBusiness: total.cancelledBusiness,
      netBusiness: total.netBusiness,
      isTotal: true,
    },
  ];

  const columns: any[] = [
    {
      title: 'Month',
      dataIndex: 'month',
      key: 'month',
      render: (val: string, record: TableRow) =>
        record.isTotal ? <strong>{val}</strong> : val,
    },
    {
      title: 'Visits',
      dataIndex: 'visits',
      key: 'visits',
      align: 'center' as const,
      render: (val: number, record: TableRow) => {
        const link = !val ? val : (
          <a
            href={buildEnquiryUrl('visits', record, financialYear, filterUserId, filterUserRole, filterAncestorIds)}
            target="_blank"
            rel="noreferrer"
            style={{ color: '#1677ff' }}
            onClick={(e) => e.stopPropagation()}
          >
            {val}
          </a>
        );
        const DNAL = record.visitsDuplicate ?? 0;
        const rv = record.visitsRepeatVisit ?? 0;
        const sumOfMonths = record.visitsSumOfMonths ?? val;
        const monthGap = sumOfMonths - val;
        return (
          <div>
            {record.isTotal ? <strong>{val}</strong> : link}
            {(DNAL > 0 || rv > 0) && (
              <div style={{ fontSize: '11px', color: '#888', fontWeight: 400 }}>
                {`DNAL: ${DNAL}, RV: ${rv}`}
                <Tooltip title="DNAL (Duplicate Number Across Launches): the same WhatsApp number visited via leads in different launches, counted once here. RV (Repeated Visits): the same WhatsApp number visited more than once (e.g. Site Visit + VC + OBM), counted once here. The number above is the count of physically distinct customers visited, after removing both.">
                  <InfoCircleOutlined style={{ fontSize: '11px', color: '#888', marginLeft: 4, cursor: 'pointer' }} />
                </Tooltip>
              </div>
            )}
            {record.isTotal && monthGap > 0 && (
              <div style={{ fontSize: '11px', color: '#888', fontWeight: 400 }}>
                {'Why not matching monthly? '}
                <Tooltip title={`If you add up each month's Visits shown above, you get ${sumOfMonths}, not ${val}. That's because each month is deduplicated on its own. This Total is deduplicated across the full year in one pass, so a customer visited in two different months (e.g. April and July) counts once here but was counted once in each of those months above. Sum of months (${sumOfMonths}) − Year total (${val}) = ${monthGap} customer(s) who revisited in a different month.`}>
                  <InfoCircleOutlined style={{ fontSize: '11px', color: '#888', cursor: 'pointer' }} />
                </Tooltip>
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: 'Tokens',
      dataIndex: 'tokens',
      key: 'tokens',
      align: 'center' as const,
      render: (val: number, record: TableRow) => {
        if (record.isTotal) return <strong>{val}</strong>;
        if (!val) return val;
        return (
          <a
            href={buildEnquiryUrl('tokens', record, financialYear, filterUserId, filterUserRole, filterAncestorIds)}
            target="_blank"
            rel="noreferrer"
            style={{ color: '#1677ff' }}
            onClick={(e) => e.stopPropagation()}
          >
            {val}
          </a>
        );
      },
    },
    {
      title: 'Bookings',
      dataIndex: 'bookings',
      key: 'bookings',
      align: 'center' as const,
      render: (val: number, record: TableRow) => {
        if (record.isTotal) return <strong>{val}</strong>;
        if (!val) return val;
        return (
          <a
            href={buildEnquiryUrl('bookings', record, financialYear, filterUserId, filterUserRole, filterAncestorIds)}
            target="_blank"
            rel="noreferrer"
            style={{ color: '#1677ff' }}
            onClick={(e) => e.stopPropagation()}
          >
            {val}
          </a>
        );
      },
    },
    {
      title: 'Cancellations',
      dataIndex: 'cancellations',
      key: 'cancellations',
      align: 'center' as const,
      render: (val: number, record: TableRow) => {
        const display = val ?? 0;
        if (record.isTotal) return <strong>{display}</strong>;
        if (!display) return display;
        const link = (
          <a
            href={buildEnquiryUrl('cancellations', record, financialYear, filterUserId, filterUserRole, filterAncestorIds)}
            target="_blank"
            rel="noreferrer"
            style={{ color: '#1677ff' }}
            onClick={(e) => e.stopPropagation()}
          >
            {display}
          </a>
        );
        // null means backend found 0 matching leads in enquiries for that month
        const gap = display - (record.enquiriesCancellations ?? 0);
        if (gap > 0) {
          return (
            <span style={{ display: 'inline-flex', alignItems: 'center' }}>
              {link}
              <Tooltip
                title={`${gap} missing cancellation${gap > 1 ? 's' : ''} in enquiries — may be revived, transferred or status changed`}
              >
                <Button
                  type="text"
                  size="small"
                  icon={<InfoCircleOutlined style={{ fontSize: 12}} />}
                  style={{ color: '#faad14' }}
                />
              </Tooltip>
            </span>
          );
        }
        return link;
      },
    },
    {
      title: 'Net Bookings',
      dataIndex: 'netBookings',
      key: 'netBookings',
      align: 'center' as const,
      render: (val: number, record: TableRow) =>
        record.isTotal ? <strong>{val}</strong> : val,
    },
  ];

  if (hasBusiness) {
    columns.push(
      {
        title: 'Business',
        dataIndex: 'business',
        key: 'business',
        align: 'right' as const,
        render: (val: number, record: TableRow) => {
          const display = val ? convertToShorthand(val) : '0';
          return record.isTotal ? <strong>{display}</strong> : display;
        },
      },
      {
        title: 'Cancelled Business',
        dataIndex: 'cancelledBusiness',
        key: 'cancelledBusiness',
        align: 'right' as const,
        render: (val: number, record: TableRow) => {
          const display = val ? convertToShorthand(val) : '0';
          return record.isTotal ? <strong>{display}</strong> : display;
        },
      },
      {
        title: 'Net Business',
        dataIndex: 'netBusiness',
        key: 'netBusiness',
        align: 'right' as const,
        render: (val: number, record: TableRow) => {
          const display = val ? convertToShorthand(val) : '0';
          return record.isTotal ? <strong>{display}</strong> : display;
        },
      },
    );
  }

  return (
    <div className="fy-monthly-section mt-6">
      <Card
        title={<Title level={4} className="mb-0">Monthly Breakdown — FY {financialYear}</Title>}
      >
        <Table
          columns={columns}
          dataSource={tableData}
          pagination={false}
          rowKey="key"
          className="analytics-table"
          rowClassName={(record: TableRow) =>
            record.isTotal ? 'analytics-total-row font-bold bg-gray-50' : ''
          }
        />
      </Card>
    </div>
  );
};

export default FYMonthlyTable;
