/* eslint-disable spellcheck/spell-checker */
'use client';
import React from 'react';
import { Form, Select, Alert, Button, Tag } from 'antd';
import type { FormInstance } from 'antd';
import type { EmployeeOption, PendingNewLaunch } from '../types';
import type { ValidatePromotionResponse } from '../service';
import NewLaunchFormCard from './NewLaunchFormCard';

const { Option } = Select;

interface Props {
  nestedEmpId: number;
  subTeamMemberCandidates: Record<number, EmployeeOption[]>;
  subTeamMemberCandidatesLoading: Record<number, boolean>;
  subSelectedTeamMemberIds: Record<number, number[]>;
  onSubTeamMembersChange: (empId: number, ids: number[]) => void;
  newLaunchFormOwnerId: number | null;
  setNewLaunchFormOwnerId: React.Dispatch<React.SetStateAction<number | null>>;
  selectedCityId: number | null;
  newLaunchForm: FormInstance;
  onCreateNewLaunch: (forUserId: number, forUserName: string) => void;
  pendingNewLaunches: PendingNewLaunch[];
  setPendingNewLaunches: React.Dispatch<React.SetStateAction<PendingNewLaunch[]>>;
  subValidations: Record<number, ValidatePromotionResponse>;
  teamMembersLabel?: string;
}

const NestedFsToTlPanel: React.FC<Props> = ({
  nestedEmpId,
  subTeamMemberCandidates,
  subTeamMemberCandidatesLoading,
  subSelectedTeamMemberIds,
  onSubTeamMembersChange,
  newLaunchFormOwnerId,
  setNewLaunchFormOwnerId,
  selectedCityId,
  newLaunchForm,
  onCreateNewLaunch,
  pendingNewLaunches,
  setPendingNewLaunches,
  subValidations,
  teamMembersLabel = 'Active Field Sales employees currently on this launch.',
}) => {
  const candidates = subTeamMemberCandidates[nestedEmpId] ?? [];
  const loading = !!subTeamMemberCandidatesLoading[nestedEmpId];
  const selected = subSelectedTeamMemberIds[nestedEmpId] ?? [];
  const isFormOpen = newLaunchFormOwnerId === nestedEmpId;

  return (
    <>
      <Form.Item
        label="Team Members"
        style={{ marginTop: 8 }}
        extra={`${teamMembersLabel} Optionally select any who should report to this new Team Leader.`}
      >
        <Select
          mode="multiple"
          placeholder="Select team members..."
          value={selected}
          onChange={(v) => onSubTeamMembersChange(nestedEmpId, v)}
          loading={loading}
          showSearch
          optionFilterProp="children"
          style={{ width: '100%' }}
        >
          {candidates.map((e) => (
            <Option key={e.id} value={e.id}>{e.name}</Option>
          ))}
        </Select>
        {!loading && candidates.length === 0 && (
          <Alert
            type="info"
            showIcon
            message="No other active Field Sales employees are currently on this launch."
            style={{ marginTop: 8 }}
          />
        )}
      </Form.Item>

      <Button
        type="dashed"
        size="small"
        onClick={() => {
          setNewLaunchFormOwnerId((v) => {
            const next = v === nestedEmpId ? null : nestedEmpId;
            if (next != null && selectedCityId) {
              newLaunchForm.setFieldsValue({ city_id: selectedCityId });
            }
            return next;
          });
        }}
        style={{ marginBottom: 8 }}
      >
        {isFormOpen ? 'Cancel New Launch' : '+ Create New Launch for this Team Leader'}
      </Button>

      {isFormOpen && (
        <NewLaunchFormCard
          form={newLaunchForm}
          selectedCityId={selectedCityId}
          forUserId={nestedEmpId}
          forUserName={subValidations[nestedEmpId]?.userName ?? ''}
          onSubmit={onCreateNewLaunch}
        />
      )}

      {pendingNewLaunches
        .filter((l) => l.forUserId === nestedEmpId)
        .map((l) => (
          <Tag
            key={l.id}
            closable
            onClose={() => setPendingNewLaunches((prev) => prev.filter((p) => p.id !== l.id))}
            style={{ marginBottom: 8 }}
          >
            New launch: {l.name}
          </Tag>
        ))}
    </>
  );
};

export default NestedFsToTlPanel;
