/* eslint-disable spellcheck/spell-checker */
'use client';
import React from 'react';
import { Card, Descriptions, Alert, Tag, Button, Typography } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import type { Dayjs } from 'dayjs';
import type { ChainMember, VacancyResolution, LeadTransferConfig, EmployeeOption, PendingNewLaunch } from '../types';
import type { ValidatePromotionResponse } from '../service';

const { Text, Title } = Typography;

interface Props {
  validation: ValidatePromotionResponse | null;
  effectiveDate: Dayjs | null;
  selectedLaunchIds: number[];
  launches: { id: number; name: string }[];
  pendingNewLaunches: PendingNewLaunch[];
  reportsToUserId: number | undefined;
  subChainMembers: ChainMember[];
  vacancyResolutions: VacancyResolution[];
  leadTransfers: LeadTransferConfig[];
  showAllSelectedLaunches: boolean;
  setShowAllSelectedLaunches: (v: boolean) => void;
  employees: EmployeeOption[];
  subEmployees: Record<string, EmployeeOption[]>;
  groupCandidates: Record<number, EmployeeOption[]>;
  getLeadRecipientOptions: (ownerId: number) => { id: number; name: string; roleName: string }[];
}

const Step5ReviewExecute: React.FC<Props> = ({
  validation, effectiveDate, selectedLaunchIds, launches, pendingNewLaunches, reportsToUserId,
  subChainMembers, vacancyResolutions, leadTransfers,
  showAllSelectedLaunches, setShowAllSelectedLaunches,
  employees, subEmployees, groupCandidates, getLeadRecipientOptions,
}) => (
  <div>
    <Title level={5} style={{ marginBottom: 16 }}>Review Promotion Chain</Title>

    <Card size="small" title="Primary Promotion" style={{ marginBottom: 16 }}>
      <Descriptions column={2} size="small">
        <Descriptions.Item label="Employee">
          <Text strong>{validation?.userName}</Text>
        </Descriptions.Item>
        <Descriptions.Item label="Role">
          {validation?.currentRoleName} <ArrowRightOutlined /> <Text strong>{validation?.toRoleName}</Text>
        </Descriptions.Item>
        <Descriptions.Item label="Designation">
          {validation?.currentDesignationName ?? '—'} <ArrowRightOutlined /> <Text strong>{validation?.toDesignationName ?? '—'}</Text>
        </Descriptions.Item>
        <Descriptions.Item label="Effective Date">
          {effectiveDate?.format('DD MMM YYYY') ?? '—'}
        </Descriptions.Item>
        {selectedLaunchIds.length > 0 && (
          <Descriptions.Item label="Launches" span={2}>
            <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 4, maxWidth: '100%' }}>
              {(showAllSelectedLaunches ? selectedLaunchIds : selectedLaunchIds.slice(0, 3)).map((id) => {
                const l = launches.find((x) => x.id === id) ?? validation?.availableLaunches?.find((x) => x.id === id);
                return (
                  <Tag key={id} color="blue" style={{ margin: 0, maxWidth: '100%', whiteSpace: 'normal' }}>
                    {l?.name ?? id}
                  </Tag>
                );
              })}
              {selectedLaunchIds.length > 3 && (
                <Button
                  type="link"
                  size="small"
                  style={{ padding: 0 }}
                  onClick={() => setShowAllSelectedLaunches(!showAllSelectedLaunches)}
                >
                  {showAllSelectedLaunches ? 'Show Less' : `+${selectedLaunchIds.length - 3} More`}
                </Button>
              )}
            </div>
          </Descriptions.Item>
        )}
        {reportsToUserId && (
          <Descriptions.Item label="Reports To">
            {validation?.availableManagers?.find((m) => m.id === reportsToUserId)?.name ?? reportsToUserId}
          </Descriptions.Item>
        )}
      </Descriptions>
    </Card>

    {subChainMembers.length > 0 && (
      <Card size="small" title="Chain Promotions" style={{ marginBottom: 16 }}>
        {subChainMembers.map((m) => (
          <div key={m.userId} style={{ marginBottom: 8 }}>
            <Text strong>{m.userName}</Text>
            {' · '}
            <Text>{m.fromRoleName}</Text>
            {' '}
            <ArrowRightOutlined style={{ color: '#1890ff' }} />
            {' '}
            <Text strong>{m.toRoleName}</Text>
            {m.toDesignationName && <Text type="secondary"> ({m.toDesignationName})</Text>}
          </div>
        ))}
      </Card>
    )}

    {vacancyResolutions.filter((r) => r.userId).length > 0 && (
      <Card size="small" title="Vacancy Assignments" style={{ marginBottom: 16 }}>
        {vacancyResolutions
          .filter((r) => r.userId)
          .map((r, i) => {
            const cacheKey = `${r.vacancy.roleId}-${r.vacancy.launchId}-${r.mode}`;
            const groupKey = r.sourceUserId ?? 0;
            const empName =
              employees.find((e) => e.id === r.userId)?.name
              ?? (subEmployees[cacheKey] ?? []).find((e) => e.id === r.userId)?.name
              ?? (groupCandidates[groupKey] ?? []).find((e) => e.id === r.userId)?.name
              ?? `User #${r.userId}`;
            return (
              <div key={i} style={{ marginBottom: 8 }}>
                <Tag color="blue">{r.vacancy.launchName}</Tag>
                <Tag color="purple">{r.vacancy.roleName}</Tag>
                {' — '}
                <Text strong>{r.mode === 'promote' ? 'Promote: ' : 'Assign: '}{empName}</Text>
              </div>
            );
          })}
      </Card>
    )}

    {leadTransfers.filter((l) => l.toUserId || l.toLaunchId).length > 0 && (
      <Card size="small" title="Lead Transfers" style={{ marginBottom: 16 }}>
        {leadTransfers
          .filter((l) => l.toUserId || l.toLaunchId)
          .map((l, i) => (
            <div key={i} style={{ marginBottom: 8 }}>
              <Text>{l.fromUserName}</Text>
              {' ('}
              <Text type="secondary">{l.fromLaunchName}</Text>
              {') '}
              <Tag color="blue">{l.leadCount} leads</Tag>
              <ArrowRightOutlined />
              {' '}
              {l.toUserId ? (
                <Text strong>
                  {getLeadRecipientOptions(l.fromUserId).find((r) => r.id === l.toUserId)?.name
                    ?? employees.find((e) => e.id === l.toUserId)?.name
                    ?? `User #${l.toUserId}`}
                </Text>
              ) : (
                <Text strong>
                  {launches.find((x) => x.id === l.toLaunchId)?.name
                    ?? validation?.availableLaunches?.find((x) => x.id === l.toLaunchId)?.name
                    ?? pendingNewLaunches.find((x) => x.id === l.toLaunchId)?.name
                    ?? `Launch #${l.toLaunchId}`}
                </Text>
              )}
            </div>
          ))}
      </Card>
    )}

    {(validation?.totalBookedLeadCount ?? 0) > 0 && (
      <Alert
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
        message={`${validation!.totalBookedLeadCount} booked lead${validation!.totalBookedLeadCount === 1 ? '' : 's'} will NOT be transferred`}
        description={
          <div>
            <Text>
              Leads already marked Booking Done stay under their current launch/manager until
              the booking is cancelled and revived — they will not follow this promotion.
            </Text>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginTop: 8 }}>
              {(validation?.bookedLeadsByLaunch ?? []).map((b) => (
                <Tag key={b.launchId} color="gold" style={{ margin: 0 }}>
                  {b.launchName}: {b.count}
                </Tag>
              ))}
            </div>
          </div>
        }
      />
    )}

    <Alert
      type="warning"
      showIcon
      message="This action is irreversible. Please review all details carefully before executing."
      style={{ marginBottom: 16 }}
    />
  </div>
);

export default Step5ReviewExecute;
