/* eslint-disable spellcheck/spell-checker */
/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';
import React from 'react';
import {
  Row, Col, Select, Alert, Table, Card, Tag, Space, Switch, Divider, Spin, Typography,
} from 'antd';
import type {
  LeadTransferConfig, LeadTransferGroup, TeamMemberStrandedRow, PendingNewLaunch,
} from '../types';
import type { ValidatePromotionResponse } from '../service';

const { Option } = Select;
const { Text, Title } = Typography;

interface Props {
  isFsToTlPromotion: boolean;
  isTlToCmPromotion: boolean;
  isTreePromotion: boolean;
  transferLeadsEnabled: boolean;
  setTransferLeadsEnabled: (v: boolean) => void;
  leadTransfers: LeadTransferConfig[];
  leadTransferGroups: LeadTransferGroup[];
  flatLeadRecipientOptions: { id: number; name: string; roleName: string }[];
  substituteEmployeesLoadingByUser: Record<number, boolean>;
  substituteLaunchesByUser: Record<number, { id: number; name: string }[]>;
  teamMemberStrandedRows: TeamMemberStrandedRow[];
  setTeamMemberStrandedRows: React.Dispatch<React.SetStateAction<TeamMemberStrandedRow[]>>;
  teamMemberStrandedLoading: boolean;
  selectedLaunchIds: number[];
  pendingNewLaunches: PendingNewLaunch[];
  launches: { id: number; name: string }[];
  validation: ValidatePromotionResponse | null;
  getLeadRecipientOptions: (ownerId: number) => { id: number; name: string; roleName: string }[];
  onLeadTransferChange: (index: number, field: 'toUserId' | 'toLaunchId', value: number | undefined) => void;
  onBulkAssignLeads: (toUserId?: number) => void;
  onLoadLaunches: () => Promise<void>;
}

const Step4LeadTransfer: React.FC<Props> = ({
  isFsToTlPromotion, isTlToCmPromotion, isTreePromotion,
  transferLeadsEnabled, setTransferLeadsEnabled,
  leadTransfers, leadTransferGroups, flatLeadRecipientOptions,
  substituteEmployeesLoadingByUser, substituteLaunchesByUser,
  teamMemberStrandedRows, setTeamMemberStrandedRows, teamMemberStrandedLoading,
  selectedLaunchIds, pendingNewLaunches, launches, validation,
  getLeadRecipientOptions, onLeadTransferChange, onBulkAssignLeads, onLoadLaunches,
}) => {
  const renderEmployeeCell = (record: LeadTransferConfig, index: number) => (
    <Select
      placeholder="Select recipient..."
      style={{ width: '100%' }}
      value={record.toUserId}
      onChange={(v) => onLeadTransferChange(index, 'toUserId', v)}
      allowClear
      showSearch
      optionFilterProp="children"
      loading={!!substituteEmployeesLoadingByUser[record.fromUserId]}
    >
      {getLeadRecipientOptions(record.fromUserId).map((m) => (
        <Option key={m.id} value={m.id}>
          {m.name}{m.roleName ? ` · ${m.roleName}` : ''}
        </Option>
      ))}
    </Select>
  );

  const renderLaunchCell = (record: LeadTransferConfig, index: number) => {
    const scopedLaunches = record.toUserId ? substituteLaunchesByUser[record.toUserId] : undefined;
    // FS→TL with no recipient: offer only the launches the new TL will oversee.
    const overseeLaunches = !record.toUserId && isFsToTlPromotion
      ? [
          ...selectedLaunchIds
            .map((id) => launches.find((x) => x.id === id) ?? validation?.availableLaunches?.find((x) => x.id === id))
            .filter((l): l is { id: number; name: string } => !!l),
          ...pendingNewLaunches,
        ]
      : undefined;
    const launchOptions = scopedLaunches ?? overseeLaunches ?? launches;

    return (
      <Select
        placeholder="Stay in launch..."
        style={{ width: '100%' }}
        value={record.toLaunchId}
        onChange={(v) => onLeadTransferChange(index, 'toLaunchId', v)}
        allowClear
        onFocus={onLoadLaunches}
        showSearch
        optionFilterProp="children"
        loading={!!record.toUserId && !scopedLaunches}
      >
        {launchOptions.map((l) => (
          <Option key={l.id} value={l.id}>{l.name}</Option>
        ))}
      </Select>
    );
  };

  return (
    <div>
      <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
        <Col>
          <Title level={5} style={{ margin: 0 }}>Configure Lead Transfers</Title>
        </Col>
        {isFsToTlPromotion && (
          <Col>
            <Space>
              <Text type="secondary">Transfer existing leads</Text>
              <Switch checked={transferLeadsEnabled} onChange={setTransferLeadsEnabled} />
            </Space>
          </Col>
        )}
      </Row>

      {isFsToTlPromotion && !transferLeadsEnabled ? (
        <Alert
          type="info"
          showIcon
          message="Lead transfer disabled for this promotion."
          description="This employee's leads will stay assigned to them under their new Team Leader role. Turn the switch on above to reassign them instead."
        />
      ) : (
        <>
          {(isTlToCmPromotion || isFsToTlPromotion) && (
            <Alert
              type="info"
              showIcon
              message={
                isTlToCmPromotion
                  ? 'Both a recipient employee and their launch are required for every row.'
                  : 'Both fields are optional. Leave them blank to keep the leads under the launches you will oversee as Team Lead.'
              }
              style={{ marginBottom: 16 }}
            />
          )}

          {!isTreePromotion && flatLeadRecipientOptions.length > 0 && (
            <Space style={{ marginBottom: 16 }}>
              <Text type="secondary">Bulk action:</Text>
              <Select
                placeholder="Transfer all to..."
                style={{ width: 240 }}
                onChange={(userId) => onBulkAssignLeads(userId)}
                allowClear
                showSearch
                optionFilterProp="children"
              >
                {flatLeadRecipientOptions.map((m) => (
                  <Option key={m.id} value={m.id}>
                    {m.name}{m.roleName ? ` · ${m.roleName}` : ''}
                  </Option>
                ))}
              </Select>
            </Space>
          )}

          {isFsToTlPromotion && (
            <>
              <Divider />
              <Title level={5} style={{ marginBottom: 12 }}>Team Member Lead Transfers</Title>
              <Spin spinning={teamMemberStrandedLoading}>
                {!teamMemberStrandedLoading && teamMemberStrandedRows.length === 0 ? (
                  <Alert
                    type="success"
                    showIcon
                    message="No team members have leads in other launches. No additional transfers needed."
                    style={{ marginBottom: 16 }}
                  />
                ) : (
                  <Table
                    dataSource={teamMemberStrandedRows}
                    rowKey={(r) => `${r.memberId}-${r.fromLaunchId}`}
                    pagination={false}
                    style={{ marginBottom: 16 }}
                    columns={[
                      { title: 'Team Member', dataIndex: 'memberName', key: 'memberName', width: 180 },
                      { title: 'From Launch', dataIndex: 'fromLaunchName', key: 'fromLaunchName', width: 200 },
                      {
                        title: <span>Target Launch <Text type="danger">*</Text></span>,
                        key: 'toLaunchId',
                        render: (_: any, record: TeamMemberStrandedRow) => (
                          <Select
                            placeholder="Select target launch..."
                            style={{ width: '100%' }}
                            value={record.toLaunchId}
                            onChange={(v) => {
                              setTeamMemberStrandedRows((prev) =>
                                prev.map((r) =>
                                  r.memberId === record.memberId && r.fromLaunchId === record.fromLaunchId
                                    ? { ...r, toLaunchId: v }
                                    : r,
                                ),
                              );
                            }}
                            showSearch
                            optionFilterProp="children"
                            onFocus={onLoadLaunches}
                          >
                            {[
                              ...selectedLaunchIds.map((id) => {
                                const l = launches.find((x) => x.id === id)
                                  ?? validation?.availableLaunches?.find((x) => x.id === id);
                                return l ? { id: l.id, name: l.name } : null;
                              }).filter((l): l is { id: number; name: string } => !!l),
                              ...pendingNewLaunches.map((l) => ({ id: l.id, name: `${l.name} (New)` })),
                            ].map((l) => (
                              <Option key={l.id} value={l.id}>{l.name}</Option>
                            ))}
                          </Select>
                        ),
                      },
                    ]}
                  />
                )}
              </Spin>
            </>
          )}

          {isTreePromotion ? (
            leadTransferGroups.map((group) => (
              <Card
                key={group.userId}
                size="small"
                style={{ marginBottom: 16 }}
                title={
                  <Space>
                    <Tag color="purple">{group.toRoleLabel} Promotion Lead Transfers</Tag>
                    <Text strong>{group.userName}{group.fromRoleLabel && ` (${group.fromRoleLabel})`}</Text>
                  </Space>
                }
              >
                <Table
                  dataSource={group.rows.map((r) => r.transfer)}
                  rowKey={(r) => `${r.fromUserId}-${r.fromLaunchId}`}
                  pagination={false}
                  columns={[
                    { title: 'Launch', dataIndex: 'fromLaunchName', key: 'fromLaunchName', width: 200 },
                    {
                      title: 'Lead Count',
                      dataIndex: 'leadCount',
                      key: 'leadCount',
                      width: 100,
                      render: (c) => <Tag color="blue">{c}</Tag>,
                    },
                    {
                      title: group.isTlToCm
                        ? <span>Transfer to Employee <Text type="danger">*</Text></span>
                        : 'Transfer to Employee',
                      key: 'toUserId',
                      render: (_: any, record: LeadTransferConfig, rowIndex: number) =>
                        renderEmployeeCell(record, group.rows[rowIndex].index),
                    },
                    {
                      title: 'Or Transfer to Launch',
                      key: 'toLaunchId',
                      render: (_: any, record: LeadTransferConfig, rowIndex: number) =>
                        renderLaunchCell(record, group.rows[rowIndex].index),
                    },
                  ]}
                />
              </Card>
            ))
          ) : (
            <Table
              dataSource={leadTransfers}
              rowKey={(r) => `${r.fromUserId}-${r.fromLaunchId}`}
              pagination={false}
              columns={[
                { title: 'Employee', dataIndex: 'fromUserName', key: 'fromUserName', width: 160 },
                { title: 'Launch', dataIndex: 'fromLaunchName', key: 'fromLaunchName', width: 160 },
                {
                  title: 'Lead Count',
                  dataIndex: 'leadCount',
                  key: 'leadCount',
                  width: 100,
                  render: (c) => <Tag color="blue">{c}</Tag>,
                },
                {
                  title: isTlToCmPromotion
                    ? <span>Transfer to Employee <Text type="danger">*</Text></span>
                    : 'Transfer to Employee',
                  key: 'toUserId',
                  render: (_: any, record: LeadTransferConfig, index: number) => renderEmployeeCell(record, index),
                },
                {
                  title: 'Or Transfer to Launch',
                  key: 'toLaunchId',
                  render: (_: any, record: LeadTransferConfig, index: number) => renderLaunchCell(record, index),
                },
              ]}
            />
          )}
        </>
      )}
    </div>
  );
};

export default Step4LeadTransfer;
