/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useRef, useState } from 'react';
import { Modal, Spin, Divider, Typography, Row, Col, Alert, Tag } from 'antd';
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  SwapOutlined,
  TrophyOutlined,
  LinkOutlined,
} from '@ant-design/icons';
import { useSession } from 'next-auth/react';
import { getDashboardTransferStats } from '../service';
import type { TransferStatsData, TransferStatsFilters } from '../interface';

const { Text, Title } = Typography;

interface TransferStatsModalProps {
  open: boolean;
  statType: 'visited' | 'token' | 'booked';
  filters: Omit<TransferStatsFilters, 'stat_type'>;
  onClose: () => void;
  /** Unique achievement count (no duplicates). */
  uniqueCount: number;
  /** Duplicate achievement count (same WhatsApp across launches). */
  duplicateCount: number;
}

const STAT_LABEL: Record<'visited' | 'token' | 'booked', string> = {
  visited: 'Visited',
  token: 'Token',
  booked: 'Booking',
};

// Roles that can see the detailed transfer breakdown (employee IN/OUT + self transfers).
// Senior roles (super_admin → cluster_manager) only see achievement + total in scope.
const INDIVIDUAL_ROLES = new Set(['team_lead', 'pre_sales', 'field_sales']);
const DIFFERENCE_LEAD_ROLES = new Set(['team_lead', 'field_sales']);

const TransferStatsModal: React.FC<TransferStatsModalProps> = ({
  open,
  statType,
  filters,
  onClose,
  uniqueCount,
  duplicateCount,
}) => {
  const totalCount = uniqueCount + duplicateCount;
  const { data: session } = useSession();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<TransferStatsData | null>(null);

  // Keep a ref to the latest filters/statType so the fetch on open always uses
  // current values without needing them in the effect dependency array.
  // This prevents re-fetching every time the parent re-renders (e.g. tab changes).
  const filtersRef = useRef(filters);
  const statTypeRef = useRef(statType);
  useEffect(() => {
    filtersRef.current = filters;
    statTypeRef.current = statType;
  });

  // Only fire the API call when the modal transitions to open.
  // Filter/statType changes while the modal is already open do NOT re-trigger.
  useEffect(() => {
    if (!open) {
      setData(null);
      setError(null);
      setLoading(false);
      return;
    }

    let cancelled = false;
    setLoading(true);
    setError(null);
    setData(null);

    const params: TransferStatsFilters = {
      stat_type: statTypeRef.current,
      ...filtersRef.current,
    };

    // Strip undefined/null/empty values
    const cleanParams: Record<string, unknown> = {};
    (Object.keys(params) as Array<keyof TransferStatsFilters>).forEach(k => {
      if (params[k] !== null && params[k] !== undefined && params[k] !== '') {
        cleanParams[k] = params[k];
      }
    });

    getDashboardTransferStats(cleanParams)
      .then((res: any) => {
        if (cancelled) return;
        const payload = res?.data ?? res;
        if (payload?.success === false) {
          setError(payload.message || 'Failed to load transfer stats.');
        } else {
          setData(payload?.data ?? null);
        }
      })
      .catch(() => {
        if (!cancelled) setError('An error occurred while loading transfer stats.');
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [open]); // ← intentionally only on open change

  const label = STAT_LABEL[statType];

  // Determine whether to show the detailed employee/self-transfer breakdown.
  // Show it only when the effective role being viewed is an individual (team_lead,
  // pre_sales, field_sales). Senior roles (super_admin → cluster_manager) that
  // have NOT drilled down to an individual only see achievement + total in scope.
  const loggedInRoleName: string = (session as any)?.user?.role?.name ?? '';
  const selectedRoleName: string = filters?.lead_user_role_name ?? '';

  // The "effective" role: if a manager drilled down to a specific user, use that
  // user's role; otherwise fall back to the logged-in user's role.
  const effectiveRole = selectedRoleName || loggedInRoleName;
  const showTransferBreakdown = INDIVIDUAL_ROLES.has(effectiveRole);
  const showDifferenceLeads = DIFFERENCE_LEAD_ROLES.has(effectiveRole);
  const showTransferSections = showTransferBreakdown && statType !== 'booked';
  const showTransferredScopeCard = statType !== 'booked';

  return (
    <Modal
      open={open}
      onCancel={onClose}
      footer={null}
      title={
        <Title level={5} style={{ margin: 0 }}>
          {label} Count Breakdown
        </Title>
      }
      width={600}
      destroyOnClose
      maskClosable={false}
      className="custom-new-modal"
      bodyStyle={{ padding: '10px 14px 14px' }}
    >
      {/* Achievement — always shown immediately from the prop; no API wait needed */}
      <div style={{ background: '#f0f5ff', borderRadius: 8, padding: '10px 12px', marginBottom: 10 }}>
        <Row align="middle" gutter={6} style={{ marginBottom: 8 }}>
          <Col>
            <TrophyOutlined style={{ fontSize: 16, color: '#1677ff' }} />
          </Col>
          <Col flex={1}>
            <Text strong style={{ fontSize: 13 }}>Current Achievement</Text>
          </Col>
        </Row>
        <Row gutter={[6, 6]}>
          <Col span={8}>
            <div style={{ background: '#e6f4ff', border: '1px solid #91caff', borderRadius: 8, padding: '4px 6px', textAlign: 'center' }}>
              <Text type="secondary" style={{ fontSize: 10, fontWeight:'bold' }}>Unique</Text>
              <div style={{ fontSize: 17, fontWeight: 700, color: '#0958d9', marginTop: 1 }}>{uniqueCount}</div>
            </div>
          </Col>
          <Col span={8}>
            <div style={{ background: '#fff7e6', border: '1px solid #ffd591', borderRadius: 8, padding: '4px 6px', textAlign: 'center' }}>
              <Text type="secondary" style={{ fontSize: 10, fontWeight:'bold' }}>Duplicate</Text>
              <div style={{ fontSize: 17, fontWeight: 700, color: '#d48806', marginTop: 1 }}>{duplicateCount}</div>
            </div>
          </Col>
          <Col span={8}>
            <div style={{ background: '#f0f5ff', border: '1px solid #adc6ff', borderRadius: 8, padding: '4px 6px', textAlign: 'center' }}>
              <Text type="secondary" style={{ fontSize: 10, fontWeight:'bold' }}>Total</Text>
              <div style={{ fontSize: 17, fontWeight: 700, color: '#1677ff', marginTop: 1 }}>{totalCount}</div>
            </div>
          </Col>
        </Row>
      </div>

      {loading && (
        <div style={{ display: 'flex', justifyContent: 'center', padding: '18px 0' }}>
          <Spin size="large" />
        </div>
      )}

      {!loading && error && (
        <Alert type="error" message={error} showIcon />
      )}

      {!loading && !error && data && (
        <>
          {/* Employee Transfer + Self Transfer sections — only for individual roles */}
          {showTransferSections && (
            <>
              <Divider style={{ margin: '8px 0' }} />

              {/* Employee Transfer Section */}
              <div style={{ marginBottom: 10 }}>
                <Row align="middle" gutter={6} style={{ marginBottom: 8 }}>
                  <Col>
                    <SwapOutlined style={{ fontSize: 14, color: '#52c41a' }} />
                  </Col>
                  <Col>
                    <Text strong style={{ fontSize: 13 }}>Employee Lead Transfers</Text>
                  </Col>
                </Row>
                <Row gutter={[10, 6]}>
                  <Col span={12}>
                    <div style={{
                      background: '#f6ffed',
                      border: '1px solid #b7eb8f',
                      borderRadius: 8,
                      padding: '6px 8px',
                    }}>
                      <Row align="middle" gutter={4}>
                        <Col>
                          <ArrowDownOutlined style={{ color: '#52c41a', fontSize: 13 }} />
                        </Col>
                        <Col>
                          <Text type="secondary" style={{ fontSize: 11, fontWeight:'bold' }}>Leads Received</Text>
                        </Col>
                      </Row>
                      <div style={{ fontSize: 18, fontWeight: 700, color: '#389e0d', marginTop: 2 }}>
                        {data.employee_transfers.leads_in}
                      </div>
                      <Tag color="green" style={{ marginTop: 3, fontSize: 9, lineHeight: '16px' }}>Transferred In</Tag>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div style={{
                      background: '#fff2e8',
                      border: '1px solid #ffbb96',
                      borderRadius: 8,
                      padding: '6px 8px',
                    }}>
                      <Row align="middle" gutter={4}>
                        <Col>
                          <ArrowUpOutlined style={{ color: '#fa8c16', fontSize: 13 }} />
                        </Col>
                        <Col>
                          <Text type="secondary" style={{ fontSize: 11, fontWeight:'bold' }}>Leads Sent Away</Text>
                        </Col>
                      </Row>
                      <div style={{ fontSize: 18, fontWeight: 700, color: '#d46b08', marginTop: 2 }}>
                        {data.employee_transfers.leads_out}
                      </div>
                      <Tag color="orange" style={{ marginTop: 3, fontSize: 9, lineHeight: '16px' }}>Transferred Out</Tag>
                    </div>
                  </Col>
                </Row>
              </div>

              {effectiveRole == 'team_lead' ? <div>
              <Divider style={{ margin: '8px 0' }} />

              {/* Self / Launch Transfer Section */}
              <div style={{ marginBottom: 10 }}>
                <Row align="middle" gutter={6} style={{ marginBottom: 8 }}>
                  <Col>
                    <LinkOutlined style={{ fontSize: 14, color: '#722ed1' }} />
                  </Col>
                  <Col>
                    <Text strong style={{ fontSize: 13 }}>Launch Transfers (Self)</Text>
                  </Col>
                </Row>
                <Row gutter={[10, 6]}>
                  <Col span={12}>
                    <div style={{
                      background: '#f9f0ff',
                      border: '1px solid #d3adf7',
                      borderRadius: 8,
                      padding: '6px 8px',
                    }}>
                      <Row align="middle" gutter={4}>
                        <Col>
                          <ArrowDownOutlined style={{ color: '#722ed1', fontSize: 13 }} />
                        </Col>
                        <Col>
                          <Text type="secondary" style={{ fontSize: 11, fontWeight:'bold' }}>Total Leads Received</Text>
                        </Col>
                      </Row>
                      <div style={{ fontSize: 18, fontWeight: 700, color: '#531dab', marginTop: 2 }}>
                        {data.self_transfers.count_in}
                      </div>
                      <Tag color="green" style={{ marginTop: 3, fontSize: 9, lineHeight: '16px' }}>Transferred In</Tag>
                    </div>
                  </Col>
                  <Col span={12}>
                    <div style={{
                      background: '#f5f0ff',
                      border: '1px solid #b37feb',
                      borderRadius: 8,
                      padding: '6px 8px',
                    }}>
                      <Row align="middle" gutter={4}>
                        <Col>
                          <ArrowUpOutlined style={{ color: '#722ed1', fontSize: 13 }} />
                        </Col>
                        <Col>
                          <Text type="secondary" style={{ fontSize: 11, fontWeight:'bold' }}>Total Leads Sent Away</Text>
                        </Col>
                      </Row>
                      <div style={{ fontSize: 18, fontWeight: 700, color: '#531dab', marginTop: 2 }}>
                        {data.self_transfers.count_out}
                      </div>
                      <Tag color="volcano" style={{ marginTop: 3, fontSize: 9, lineHeight: '16px' }}>Transferred Out</Tag>
                    </div>
                  </Col>
                </Row>
              </div>
              </div> : null}
            </>
          )}

          {showTransferredScopeCard && (
            <>
              <Divider style={{ margin: '8px 0' }} />

              {/* Total Transferred in Scope — shown for all roles, filtered to the stat type */}
              <div style={{
                background: '#fffbe6',
                border: '1px solid #ffe58f',
                borderRadius: 8,
                padding: '6px 8px',
              }}>
                <Row justify="space-between" align="middle">
                  <Col>
                    <Text strong style={{ fontSize: 12 }}>
                      Total {label} Leads Transferred in Scope
                    </Text>
                    <br />
                    <Text type="secondary" style={{ fontSize: 10 }}>
                      Unique {label.toLowerCase()} leads involved in any transfer (matches Enquiries filtered view)
                    </Text>
                  </Col>
                  <Col>
                    <span style={{ fontSize: 18, fontWeight: 700, color: '#d48806' }}>
                      {data.total_transferred_leads_in_scope}
                    </span>
                  </Col>
                </Row>
              </div>
            </>
          )}

          {/* Difference Leads table — only for field_sales / team_lead on visited/booked card */}
          {showDifferenceLeads && (statType === 'visited' || statType === 'booked') && !!data.difference_leads?.count && (
            <>
              <Divider style={{ margin: '8px 0' }} />
              <div>
                <Row align="middle" gutter={6} style={{ marginBottom: 6 }}>
                  <Col>
                    <Text strong style={{ fontSize: 12, color: '#cf1322' }}>
                      {statType === 'visited' ? 'Visit Done By Team Mates' : 'Booked By Team Mates'}
                    </Text>
                  </Col>
                  <Col>
                    <Tag color="red" style={{ marginInlineEnd: 0, fontSize: 10, lineHeight: '16px' }}>{data.difference_leads?.count || 0} lead{(data.difference_leads?.count || 0) !== 1 ? 's' : ''}</Tag>
                  </Col>
                </Row>
                <Text type="secondary" style={{ fontSize: 10, display: 'block', marginBottom: 6, lineHeight: 1.35 }}>
                  {statType === 'visited' 
                    ? 'These leads are assigned to you and have a site visit / VC / OBM — but the visit was recorded by someone else, so they appear in Enquiries but not in your dashboard achievement.'
                    : 'These leads are assigned to you and are booked — but the booking was recorded by someone else, so they appear in Enquiries but not in your dashboard achievement.'}
                </Text>
                <div className="custom-scrollbar" style={{ maxHeight: 212, overflowY: 'auto', border: '1px solid #ffccc7', borderRadius: 6 }}>
                  <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 11 }}>
                    <thead>
                      <tr style={{ background: '#fff1f0', position: 'sticky', top: 0, zIndex: 1 }}>
                        <th style={{ padding: '5px 7px', textAlign: 'left', borderBottom: '1px solid #ffccc7', fontWeight: 600 }}>Customer</th>
                        <th style={{ padding: '5px 7px', textAlign: 'left', borderBottom: '1px solid #ffccc7', fontWeight: 600 }}>Status</th>
                        <th style={{ padding: '5px 7px', textAlign: 'left', borderBottom: '1px solid #ffccc7', fontWeight: 600 }}>{statType === 'visited' ? 'Visited By' : 'Booked By'}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {data.difference_leads!.rows.map((row, i) => (
                        <tr
                          key={row.lead_id}
                          style={{ background: i % 2 === 0 ? '#fff' : '#fff8f8', cursor: 'pointer', transition: 'background-color 120ms ease' }}
                          onMouseEnter={(e) => {
                            e.currentTarget.style.background = '#ffdede';
                          }}
                          onMouseLeave={(e) => {
                            e.currentTarget.style.background = i % 2 === 0 ? '#fff' : '#fff8f8';
                          }}
                          onClick={() => window.open(`/enquiries?id=${row.lead_id}`, '_blank')}
                        >
                          <td style={{ padding: '4px 7px', borderBottom: '1px solid #ffd6d6' }}>
                            <div>{row.customer_name || '—'}</div>
                            <div style={{ color: '#888', fontSize: 9 }}>{row.whatsApp_number || ''}</div>
                          </td>
                          <td style={{ padding: '4px 7px', borderBottom: '1px solid #ffd6d6' }}>
                            <Tag color="blue" style={{ fontSize: 9, lineHeight: '16px', marginInlineEnd: 0 }}>{row.current_status || '—'}</Tag>
                          </td>
                          <td style={{ padding: '4px 7px', borderBottom: '1px solid #ffd6d6', maxWidth: 130, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                            {statType === 'visited' ? (row as any).visited_by_names || '—' : (row as any).booked_by_names || '—'}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            </>
          )}
        </>
      )}
    </Modal>
  );
};

export default TransferStatsModal;
