import React, { useEffect, useState } from 'react';
import { Empty, Spin, Tag, Typography } from 'antd';
import { getSmsRotationPreview } from '../service';
import type { SmsPoolRow } from '../interface';

const { Text } = Typography;

const AVATAR_COLORS = ['#16a34a', '#2563eb', '#7c3aed', '#d97706', '#dc2626', '#0891b2'];

function colorForUser(userId: number): string {
  return AVATAR_COLORS[userId % AVATAR_COLORS.length];
}

function initialsFor(name: string): string {
  const parts = name.trim().split(/\s+/);
  return ((parts[0]?.[0] || '') + (parts[1]?.[0] || '')).toUpperCase();
}

function roleLabel(role: string): string {
  return role === 'field-sales' ? 'Field Sales' : role === 'pre-sales' ? 'Pre Sales' : 'Team Lead';
}

interface SmsRotationPreviewProps {
  projectId?: number;
  /* Bumped by the parent after a save, so the preview re-syncs and reflects
   * anything the save itself changed (e.g. a first-time pool build). */
  refreshKey?: number;
}

/*
  Read-only — there is nothing to configure here. Unlike Facebook/Google,
  an SMS rotation's seller pool is entirely derived from projects.seller_id
  and each seller's own current Sustenance launch (see
  housieyCampaign.helper.js); it is rebuilt on every incoming lead, not saved
  from this screen. This just shows what that derivation currently produces,
  so an admin can see who's in line — and why nobody is, when the pool is
  empty — before any SMS goes out.
 */
const SmsRotationPreview: React.FC<SmsRotationPreviewProps> = ({ projectId, refreshKey }) => {
  const [rows, setRows] = useState<SmsPoolRow[]>([]);
  const [totalSellers, setTotalSellers] = useState(0);
  const [emptyReason, setEmptyReason] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!projectId) {
      setRows([]);
      return;
    }
    setLoading(true);
    getSmsRotationPreview(projectId)
      .then((res) => {
        setRows(res.data);
        setTotalSellers(res.total_sellers);
        setEmptyReason(res.empty_reason);
      })
      .finally(() => setLoading(false));
  }, [projectId, refreshKey]);

  if (!projectId) return null;

  return (
    <div>
      <div className="flex items-center justify-between mb-2">
        <Text type="secondary" style={{ fontSize: 11 }}>
          ROTATION PREVIEW — DERIVED FROM THIS PROJECT&apos;S SELLERS
        </Text>
        {rows.length > 0 && (
          <Text type="secondary" style={{ fontSize: 12 }}>
            {rows.length} seller{rows.length === 1 ? '' : 's'} in rotation
          </Text>
        )}
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-6">
          <Spin />
        </div>
      ) : rows.length === 0 ? (
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={
            <span style={{ fontSize: 13 }}>
              {emptyReason || (totalSellers === 0 ? 'This project has no sellers configured.' : 'No eligible sellers.')}
            </span>
          }
        />
      ) : (
        rows.map((row, index) => (
          <div
            key={row.seller_id}
            className="flex items-center gap-3 rounded-md border border-gray-100 bg-white px-3 py-2 mb-2 shadow-sm">
            <Text type="secondary" style={{ width: 20, fontSize: 12 }}>
              {String(index + 1).padStart(2, '0')}
            </Text>
            <div
              style={{
                width: 28,
                height: 28,
                borderRadius: '50%',
                background: colorForUser(row.seller_id),
                color: '#fff',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                fontSize: 12,
                flexShrink: 0,
              }}>
              {initialsFor(row.seller_name)}
            </div>
            <Text strong style={{ flex: 1 }}>
              {row.seller_name}
            </Text>
            <Text type="secondary" style={{ fontSize: 11, width: 80 }}>
              {roleLabel(row.role)}
            </Text>
            <Tag color="blue" style={{ fontSize: 11 }}>{row.launch_name}</Tag>
            <Text type="secondary" style={{ fontSize: 12, width: 70, textAlign: 'right' }}>
              {row.assigned_count}/{row.no_of_lead}
            </Text>
          </div>
        ))
      )}
    </div>
  );
};

export default SmsRotationPreview;
