/* eslint-disable spellcheck/spell-checker */
'use client';
import React, { useEffect, useState, useCallback } from 'react';
import { Modal, Table, Tag, Typography } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getAnalyticsDrillDown } from '../service';
import { DrillDownLead, AnalyticsParams } from '../interface';
import { convertToShorthand } from '@/utills/helper';

const { Text } = Typography;

const STATUS_LABEL: Record<number, string> = {
  14: 'Site Visit Done',
  15: 'VC Done',
  16: 'OBM Done',
  17: 'Token Done',
  18: 'Booking Done',
  19: 'Booking Cancelled',
};

const STATUS_COLOR: Record<number, string> = {
  14: 'blue',
  15: 'cyan',
  16: 'geekblue',
  17: 'gold',
  18: 'green',
  19: 'red',
};

const METRIC_LABEL: Record<string, string> = {
  visits: 'Visits',
  tokens: 'Tokens',
  bookings: 'Bookings',
  cancellations: 'Cancellations',
};

const METRIC_DATE_COL: Record<string, keyof DrillDownLead> = {
  visits: 'site_visited_at',
  tokens: 'token_date',
  bookings: 'booked_at',
  cancellations: 'booked_at',
};

export interface DrillDownTarget {
  metric: 'visits' | 'tokens' | 'bookings' | 'cancellations';
  monthNumber: number;
  year: number;
  monthLabel: string;
}

interface DrillDownModalProps {
  target: DrillDownTarget | null;
  filterParams: AnalyticsParams;
  showBusiness?: boolean;
  onClose: () => void;
}

const DrillDownModal: React.FC<DrillDownModalProps> = ({ target, filterParams, showBusiness = true, onClose }) => {
  const [leads, setLeads] = useState<DrillDownLead[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const pageSize = 20;

  const fetchLeads = useCallback(async (p: number) => {
    if (!target) return;
    setLoading(true);
    try {
      const res = await getAnalyticsDrillDown({
        ...filterParams,
        metric: target.metric,
        month_number: target.monthNumber,
        year: target.year,
        page: p,
        page_size: pageSize,
      });
      const data = res?.data?.data;
      setLeads(data?.leads || []);
      setTotal(data?.total || 0);
    } catch {
      setLeads([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, [target, filterParams]);

  useEffect(() => {
    if (target) {
      setPage(1);
      fetchLeads(1);
    }
  }, [target, fetchLeads]);

  const dateCol = target ? METRIC_DATE_COL[target.metric] : 'booked_at';

  const columns: ColumnsType<DrillDownLead> = [
    {
      title: '#',
      key: 'index',
      width: 50,
      render: (_: any, __: any, index: number) => (page - 1) * pageSize + index + 1,
    },
    {
      title: 'Customer',
      dataIndex: 'customer_name',
      key: 'customer_name',
      render: (name: string, record: DrillDownLead) => (
        <div>
          <div>{name || '—'}</div>
          <Text type="secondary" style={{ fontSize: 12 }}>{record.whatsApp_number}</Text>
        </div>
      ),
    },
    {
      title: 'Project',
      dataIndex: 'project_name',
      key: 'project_name',
      render: (val: string) => val || '—',
    },
    {
      title: METRIC_LABEL[target?.metric || 'visits'] + ' Date',
      dataIndex: dateCol as string,
      key: 'date',
      render: (val: string) => val ? new Date(val).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' }) : '—',
    },
    {
      title: 'Field Sales',
      dataIndex: 'field_sales_name',
      key: 'field_sales_name',
      render: (val: string) => val?.trim() || '—',
    },
    {
      title: 'Pre Sales',
      dataIndex: 'pre_sales_name',
      key: 'pre_sales_name',
      render: (val: string) => val?.trim() || '—',
    },
    {
      title: 'Status',
      dataIndex: 'current_status',
      key: 'current_status',
      render: (status: number) => (
        <Tag color={STATUS_COLOR[status] || 'default'}>
          {STATUS_LABEL[status] || `Status ${status}`}
        </Tag>
      ),
    },
  ];

  if (showBusiness && (target?.metric === 'bookings' || target?.metric === 'cancellations')) {
    columns.push({
      title: 'Agreement Value',
      dataIndex: 'agreement_value',
      key: 'agreement_value',
      align: 'right',
      render: (val: number | null) => val ? convertToShorthand(val) : '—',
    });
  }

  const title = target
    ? `${METRIC_LABEL[target.metric]} — ${target.monthLabel}`
    : '';

  return (
    <Modal
      open={!!target}
      title={<strong>{title}</strong>}
      onCancel={onClose}
      footer={null}
      width={900}
      destroyOnClose
    >
      <Table<DrillDownLead>
        columns={columns}
        dataSource={leads}
        rowKey="lead_id"
        loading={loading}
        pagination={{
          current: page,
          pageSize,
          total,
          showTotal: (t) => `${t} leads`,
          onChange: (p) => {
            setPage(p);
            fetchLeads(p);
          },
        }}
        size="small"
        scroll={{ x: 800 }}
      />
    </Modal>
  );
};

export default DrillDownModal;
