'use client';
import { useEffect, useState } from 'react';
import { Form, Select, Input, DatePicker, Spin } from 'antd';
import { FormDrawer } from '@/components/ui/drawers/FormDrawer';
import { applicationsApi } from '@/services/api';

interface Props {
  open: boolean;
  loading?: boolean;
  onClose: () => void;
  onSubmit: (data: ScheduleInterviewData) => void;
}

export interface ScheduleInterviewData {
  application_id: string;
  scheduled_at: string;
  interview_type?: string;
  location?: string;
  meeting_link?: string;
  notes?: string;
  interviewer_name?: string;
}

const TYPE_OPTIONS = [
  { value: 'in_person', label: 'In-Person' },
  { value: 'phone', label: 'Phone' },
  { value: 'video', label: 'Video Call' },
  { value: 'walk_in', label: 'Walk-In' },
];

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const fmtDateTime = (v: unknown): string | null => (v && (v as any).toISOString ? (v as any).toISOString() : null);

export function ScheduleInterviewDrawer({ open, loading, onClose, onSubmit }: Props) {
  const [form] = Form.useForm();
  const [applications, setApplications] = useState<{ value: string; label: string; sub: string }[]>([]);
  const [appsLoading, setAppsLoading] = useState(false);

  useEffect(() => {
    if (!open) return;
    setAppsLoading(true);
    applicationsApi.getAll({ limit: 200, page: 1, status: 'shortlisted' })
      .then((res) => setApplications(res.data.map((a) => ({
        value: a.id,
        label: `${a.applicant_name} → ${a.job_title}`,
        sub: a.company_name,
      }))))
      .catch(() => {})
      .finally(() => setAppsLoading(false));
  }, [open]);

  const handleClose = () => { form.resetFields(); onClose(); };

  const handleFinish = (values: Record<string, unknown>) => {
    const scheduledAt = fmtDateTime(values.scheduled_at);
    if (!scheduledAt) return;
    onSubmit({
      application_id: values.application_id as string,
      scheduled_at: scheduledAt,
      interview_type: values.interview_type as string | undefined,
      location: values.location as string | undefined,
      meeting_link: values.meeting_link as string | undefined,
      notes: values.notes as string | undefined,
      interviewer_name: values.interviewer_name as string | undefined,
    });
    handleClose();
  };

  return (
    <FormDrawer
      title="Schedule Interview"
      subtitle="Schedule a new interview for a shortlisted applicant"
      open={open}
      onClose={handleClose}
      onSubmit={() => form.submit()}
      loading={loading}
      submitLabel="Schedule Interview"
    >
      <Form form={form} layout="vertical" onFinish={handleFinish}>
        <Form.Item
          name="application_id"
          label="Select Application (Shortlisted)"
          rules={[{ required: true, message: 'Please select an application' }]}
        >
          <Select
            showSearch
            allowClear
            placeholder={appsLoading ? 'Loading applications...' : 'Search applicant or job...'}
            notFoundContent={appsLoading ? <Spin size="small" /> : 'No shortlisted applications found'}
            filterOption={(input, opt) =>
              (opt?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            optionRender={(opt) => {
              const app = applications.find((a) => a.value === opt.value);
              return (
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500 }}>{opt.label}</div>
                  {app?.sub && <div style={{ fontSize: 11, color: '#94a3b8' }}>{app.sub}</div>}
                </div>
              );
            }}
            options={applications.map((a) => ({ value: a.value, label: a.label }))}
          />
        </Form.Item>

        <Form.Item
          name="scheduled_at"
          label="Interview Date & Time"
          rules={[{ required: true, message: 'Please select date and time' }]}
        >
          <DatePicker showTime style={{ width: '100%' }} format="DD/MM/YYYY HH:mm" placeholder="Select date and time" />
        </Form.Item>

        <Form.Item name="interview_type" label="Interview Type" initialValue="in_person">
          <Select options={TYPE_OPTIONS} />
        </Form.Item>

        <Form.Item name="location" label="Location (for in-person/walk-in)">
          <Input placeholder="Office address or venue..." />
        </Form.Item>

        <Form.Item name="meeting_link" label="Meeting Link (for video)">
          <Input placeholder="https://meet.google.com/..." />
        </Form.Item>

        <Form.Item name="interviewer_name" label="Interviewer Name">
          <Input placeholder="HR Manager name..." />
        </Form.Item>

        <Form.Item name="notes" label="Notes / Instructions">
          <Input.TextArea rows={3} placeholder="Bring original documents, dress code, etc." />
        </Form.Item>
      </Form>
    </FormDrawer>
  );
}
