/* eslint-disable spellcheck/spell-checker */
'use client';
import React from 'react';
import { Card, Form, Row, Col, Select, Descriptions, Spin, Tag, Typography } from 'antd';
import { ArrowRightOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd';
import type { EmployeeOption } from '../types';
import type { ValidatePromotionResponse } from '../service';
import MasterCities from '@/components/masterDropdowns/MasterCities';

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

interface TargetRole {
  id: number;
  label: string;
  name: string;
}

interface Props {
  selectedCityId: number | null;
  employees: EmployeeOption[];
  empLoading: boolean;
  selectedEmployee: EmployeeOption | null;
  targetRoleId: number | null;
  targetDesignationId: number | null;
  validation: ValidatePromotionResponse | null;
  validationLoading: boolean;
  designationsByRole: Record<number, { id: number; name: string }[]>;
  designationsLoadingRoleIds: Record<number, boolean>;
  targetRoles: TargetRole[];
  step1Form: FormInstance;
  onCitySelect: (cityId: number | string) => void;
  onCityClear: () => void;
  onEmployeeSearch: (search: string) => void;
  onEmployeeSelect: (empId: number) => void;
  onEmployeeClear: () => Promise<void>;
  onTargetRoleSelect: (roleId: number) => void;
  onTargetRoleClear: () => void;
  onTargetDesignationSelect: (designationId: number) => Promise<void>;
  onTargetDesignationClear: () => void;
}

const Step1SelectEmployee: React.FC<Props> = ({
  selectedCityId, employees, empLoading, selectedEmployee,
  targetRoleId, targetDesignationId, validation, validationLoading,
  designationsByRole, designationsLoadingRoleIds, targetRoles,
  step1Form, onCitySelect, onCityClear, onEmployeeSearch, onEmployeeSelect,
  onEmployeeClear, onTargetRoleSelect, onTargetRoleClear,
  onTargetDesignationSelect, onTargetDesignationClear,
}) => (
  <div>
    <Title level={5} style={{ marginBottom: 16 }}>Select Employee to Promote</Title>
    <Row gutter={16}>
      <Col xs={24} md={6}>
        <Form form={step1Form}>
          <MasterCities
            label="City"
            name="city_id"
            placeholder="Select City"
            filter={{ status: 'active' }}
            rules={[{ required: true, message: 'Please select a city' }]}
            // Re-seeds the field on remount so the picker doesn't blank when navigating back to Step 1.
            initialValue={selectedCityId ?? undefined}
            onChange={(value) => onCitySelect(value)}
            onClear={onCityClear}
          />
        </Form>
      </Col>

      <Col xs={24} md={6}>
        <Form.Item label="Employee" required>
          <Select
            showSearch
            placeholder={selectedCityId ? 'Search by name...' : 'Select a city first'}
            filterOption={false}
            disabled={!selectedCityId}
            onSearch={onEmployeeSearch}
            loading={empLoading}
            onChange={onEmployeeSelect}
            value={selectedEmployee?.id}
            allowClear
            onClear={onEmployeeClear}
          >
            {employees.map((e) => (
              <Option key={e.id} value={e.id}>
                {e.name}
                {e.roleName && <Text type="secondary"> · {e.roleName}</Text>}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Col>

      <Col xs={24} md={6}>
        <Form.Item label="Promote to Role" required>
          <Select
            placeholder="Select target role"
            disabled={!selectedEmployee}
            value={targetRoleId}
            onChange={onTargetRoleSelect}
            allowClear
            onClear={onTargetRoleClear}
          >
            {targetRoles.map((r) => (
              <Option key={r.id} value={r.id}>{r.label}</Option>
            ))}
          </Select>
        </Form.Item>
      </Col>

      <Col xs={24} md={6}>
        <Form.Item label="Promote to Designation" required>
          <Select
            placeholder={targetRoleId ? 'Select target designation' : 'Select a role first'}
            disabled={!targetRoleId}
            loading={!!targetRoleId && !!designationsLoadingRoleIds[targetRoleId]}
            value={targetDesignationId ?? undefined}
            onChange={onTargetDesignationSelect}
            allowClear
            onClear={onTargetDesignationClear}
          >
            {(targetRoleId ? designationsByRole[targetRoleId] ?? [] : []).map((d) => (
              <Option key={d.id} value={d.id}>{d.name}</Option>
            ))}
          </Select>
        </Form.Item>
      </Col>
    </Row>

    {validationLoading && (
      <div style={{ textAlign: 'center', padding: 24 }}>
        <Spin tip="Validating promotion..." />
      </div>
    )}

    {validation && !validationLoading && (
      <Card
        size="small"
        style={{ marginTop: 16, background: '#fafafa', border: '1px solid #e8e8e8' }}
        title="Promotion Preview"
      >
        <Descriptions column={2} size="small">
          <Descriptions.Item label="Employee">
            <Text strong>{validation.userName}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="Role">
            {validation.currentRoleName}{' '}
            <ArrowRightOutlined style={{ color: '#1890ff' }} />{' '}
            <Text strong>{validation.toRoleName}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="Designation">
            {validation.currentDesignationName ?? '—'}{' '}
            <ArrowRightOutlined style={{ color: '#1890ff' }} />{' '}
            <Text strong>{validation.toDesignationName ?? '—'}</Text>
          </Descriptions.Item>
          <Descriptions.Item label="Vacancies to Fill">
            <Tag color={validation.vacancies?.length ? 'orange' : 'green'}>
              {validation.vacancies?.length ?? 0} vacanc{(validation.vacancies?.length ?? 0) !== 1 ? 'ies' : 'y'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="Lead Transfer Required">
            <Tag color={validation.needsLeadTransfer ? 'orange' : 'green'}>
              {validation.needsLeadTransfer ? 'Yes' : 'No'}
            </Tag>
          </Descriptions.Item>
          <Descriptions.Item label="Launch Assignment Required">
            <Tag color={validation.needsLaunchAssignment ? 'orange' : 'green'}>
              {validation.needsLaunchAssignment ? 'Yes' : 'No'}
            </Tag>
          </Descriptions.Item>
        </Descriptions>
      </Card>
    )}
  </div>
);

export default Step1SelectEmployee;
