/* eslint-disable spellcheck/spell-checker */
/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';
import React from 'react';
import {
  Form, Row, Col, Select, DatePicker, Divider, Space, Tag, Button, Alert, Checkbox, Tooltip, Typography,
} from 'antd';
import { LockOutlined, DeleteOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd';
import type { Dayjs } from 'dayjs';
import type { EmployeeOption, PendingNewLaunch } from '../types';
import type { ValidatePromotionResponse } from '../service';
import NewLaunchFormCard from '../components/NewLaunchFormCard';

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

interface Props {
  effectiveDate: Dayjs | null;
  setEffectiveDate: (date: Dayjs | null) => void;
  reportsToUserId: number | undefined;
  setReportsToUserId: (id: number | undefined) => void;
  validation: ValidatePromotionResponse | null;
  selectedLaunchIds: number[];
  setSelectedLaunchIds: (ids: number[]) => void;
  lockedLaunchIds: number[];
  preselectedLaunchIds: number[];
  launches: { id: number; name: string }[];
  isFsToTlPromotion: boolean;
  isTreePromotion: boolean;
  teamMemberCandidates: EmployeeOption[];
  teamMemberCandidatesLoading: boolean;
  selectedTeamMemberIds: number[];
  setSelectedTeamMemberIds: (ids: number[]) => void;
  selectedEmployee: EmployeeOption | null;
  selectedCityId: number | null;
  newLaunchForm: FormInstance;
  newLaunchFormOwnerId: number | null;
  setNewLaunchFormOwnerId: React.Dispatch<React.SetStateAction<number | null>>;
  pendingNewLaunches: PendingNewLaunch[];
  setPendingNewLaunches: React.Dispatch<React.SetStateAction<PendingNewLaunch[]>>;
  onLoadLaunches: () => Promise<void>;
  onCreateNewLaunch: (forUserId: number, forUserName: string) => Promise<void>;
  disabledDate: (current: Dayjs) => boolean;
}

const Step2NewAssignment: React.FC<Props> = ({
  effectiveDate, setEffectiveDate, reportsToUserId, setReportsToUserId,
  validation, selectedLaunchIds, setSelectedLaunchIds, lockedLaunchIds,
  preselectedLaunchIds, launches, isFsToTlPromotion, isTreePromotion,
  teamMemberCandidates, teamMemberCandidatesLoading, selectedTeamMemberIds,
  setSelectedTeamMemberIds, selectedEmployee, selectedCityId,
  newLaunchForm, newLaunchFormOwnerId, setNewLaunchFormOwnerId,
  pendingNewLaunches, setPendingNewLaunches, onLoadLaunches, onCreateNewLaunch, disabledDate,
}) => (
  <div>
    <Title level={5} style={{ marginBottom: 16 }}>Configure New Assignment</Title>

    <Row gutter={16}>
      <Col xs={24} md={12}>
        <Form.Item label="Effective Date" required>
          <DatePicker
            style={{ width: '100%' }}
            value={effectiveDate}
            onChange={(date) => setEffectiveDate(date)}
            disabledDate={disabledDate}
            format="DD MMM YYYY"
          />
        </Form.Item>
      </Col>
      <Col xs={24} md={12}>
        <Form.Item label="Reports To" required={(validation?.availableManagers?.length ?? 0) > 0}>
          <Select
            placeholder="Select reporting manager"
            value={reportsToUserId}
            onChange={(v) => setReportsToUserId(v)}
            allowClear
            onClear={() => setReportsToUserId(undefined)}
            showSearch
            optionFilterProp="children"
          >
            {(validation?.availableManagers ?? []).map((m) => (
              <Option key={m.id} value={m.id}>
                {m.name}
                {m.roleName && <Text type="secondary"> · {m.roleName}</Text>}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Col>
    </Row>

    {validation?.needsLaunchAssignment && (
      <div>
        <Divider />
        <Form.Item
          label="Launches to Oversee"
          required
          extra={
            lockedLaunchIds.length
              ? 'Select the launches this employee will manage in their new role. Launches they are already assigned to are carried over automatically and cannot be removed.'
              : 'Select the launches this employee will manage in their new role.'
          }
        >
          <Select
            mode="multiple"
            placeholder="Select launches..."
            value={selectedLaunchIds}
            onChange={(v) => {
              // Locked launches (e.g. FS carryover) can't be removed — re-merge if backspace slips one through.
              const next = lockedLaunchIds.length
                ? Array.from(new Set([...v, ...lockedLaunchIds]))
                : v;
              setSelectedLaunchIds(next);
            }}
            onFocus={onLoadLaunches}
            showSearch
            optionLabelProp="label"
            optionFilterProp="label"
            menuItemSelectedIcon={null}
            tagRender={({ label, value, closable, onClose }) => {
              const isLocked = lockedLaunchIds.includes(value as number);
              return (
                <Tag
                  closable={isLocked ? false : closable}
                  onClose={onClose}
                  icon={isLocked ? <LockOutlined /> : undefined}
                  style={{ marginRight: 3 }}
                >
                  {label}
                </Tag>
              );
            }}
            style={{ width: '100%' }}
          >
            {(validation?.availableLaunches?.length ? validation.availableLaunches : launches).map((l) => {
              const isLocked = lockedLaunchIds.includes(l.id);
              return (
                <Option key={l.id} value={l.id} label={l.name} disabled={isLocked}>
                  <Space>
                    <Checkbox checked={selectedLaunchIds.includes(l.id)} disabled={isLocked} />
                    <span>{l.name}</span>
                    {isLocked && (
                      <Tooltip title="Already assigned to this employee — cannot be removed">
                        <LockOutlined style={{ color: '#999' }} />
                      </Tooltip>
                    )}
                  </Space>
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        {(isFsToTlPromotion || isTreePromotion) && (
          <Form.Item
            label="Team Members"
            required={false}
            extra={
              isFsToTlPromotion
                ? selectedLaunchIds.length === 0 && preselectedLaunchIds.length > 0
                  ? 'Field Sales and Pre-Sales colleagues currently reporting to the same manager. Optionally select the ones you want to assign to this new Team Leader.'
                  : 'Active Field Sales employees currently on the selected launches. Optionally select any you want to assign to this new Team Leader.'
                : 'Active employees currently reporting to the same manager as this employee. Optionally select any who should report to the newly promoted employee instead.'
            }
          >
            <Select
              mode="multiple"
              placeholder={
                isFsToTlPromotion && selectedLaunchIds.length === 0 && preselectedLaunchIds.length === 0
                  ? 'Select launches first...'
                  : 'Select team members...'
              }
              value={selectedTeamMemberIds}
              onChange={(v) => setSelectedTeamMemberIds(v)}
              loading={teamMemberCandidatesLoading}
              disabled={isFsToTlPromotion && selectedLaunchIds.length === 0 && preselectedLaunchIds.length === 0}
              showSearch
              optionFilterProp="children"
              style={{ width: '100%' }}
            >
              {teamMemberCandidates.map((e) => (
                <Option key={e.id} value={e.id}>
                  {e.name}
                  {e.roleName && <Text type="secondary"> · {e.roleName}</Text>}
                </Option>
              ))}
            </Select>
            {!teamMemberCandidatesLoading &&
              (!isFsToTlPromotion || selectedLaunchIds.length > 0) &&
              teamMemberCandidates.length === 0 && (
              <Alert
                type="info"
                showIcon
                message={
                  isFsToTlPromotion
                    ? 'No active Field Sales employees are currently on the selected launches.'
                    : 'No other active employees currently report to the same manager.'
                }
                style={{ marginTop: 8 }}
              />
            )}
          </Form.Item>
        )}

        {validation?.canCreateLaunch && selectedEmployee && (
          <Button
            type="dashed"
            size="small"
            onClick={() => {
              setNewLaunchFormOwnerId((v) => {
                const next = v === selectedEmployee.id ? null : selectedEmployee.id;
                if (next != null && selectedCityId) {
                  newLaunchForm.setFieldsValue({ city_id: selectedCityId });
                }
                return next;
              });
            }}
            style={{ marginBottom: 16 }}
          >
            {newLaunchFormOwnerId === selectedEmployee.id ? 'Cancel New Launch' : '+ Create New Launch'}
          </Button>
        )}

        {validation?.canCreateLaunch && selectedEmployee && newLaunchFormOwnerId === selectedEmployee.id && (
          <div style={{ marginBottom: 16 }}>
            <Title level={5} style={{ marginBottom: 12 }}>New Launch Details</Title>
            <NewLaunchFormCard
              form={newLaunchForm}
              selectedCityId={selectedCityId}
              forUserId={selectedEmployee.id}
              forUserName={selectedEmployee.name}
              onSubmit={onCreateNewLaunch}
            />
          </div>
        )}

        {pendingNewLaunches.length > 0 && (
          <div style={{ marginBottom: 16, background: '#fafafa', border: '1px solid #f0f0f0', borderRadius: 8, padding: 12 }}>
            <Space style={{ marginBottom: 8 }}>
              <Text strong>Launches to Create</Text>
              <Tag>{pendingNewLaunches.length}</Tag>
            </Space>
            <Space direction="vertical" style={{ width: '100%' }} size={8}>
              {pendingNewLaunches.map((l, i) => (
                <Row
                  key={l.id}
                  justify="space-between"
                  align="middle"
                  style={{ padding: '6px 12px', background: '#fff', border: '1px solid #f0f0f0', borderRadius: 4 }}
                >
                  <Col>
                    <Text>{l.name}</Text>
                    {l.forUserName && <Text type="secondary"> — for {l.forUserName}</Text>}
                  </Col>
                  <Col>
                    <Button
                      type="text"
                      danger
                      size="small"
                      icon={<DeleteOutlined />}
                      onClick={() => setPendingNewLaunches((prev) => prev.filter((_, idx) => idx !== i))}
                    />
                  </Col>
                </Row>
              ))}
            </Space>
            <Text type="secondary" style={{ display: 'block', marginTop: 8, fontSize: 12 }}>
              Not yet saved — for reference only.
            </Text>
          </div>
        )}
      </div>
    )}
  </div>
);

export default Step2NewAssignment;
