'use client';
import { useEffect, useState } from 'react';
import { Form, Switch, Row, Col, Divider, Typography, Spin } from 'antd';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { FormDrawer } from '@/components/ui/drawers/FormDrawer';
import { AppSelect } from '@/components/ui/selects/AppSelect';
import { AppInputNumber } from '@/components/ui/inputs/AppInputNumber';
import { employersApi } from '@/services/api';
import type { UploadResult } from '@/components/ui/uploader';
import { JobDynamicFormSections } from './JobDynamicFormSections';
import { extractDynamicFieldValue } from '@/modules/dynamic-fields/dynamic-field-value.util';
import { jobFormSchema, type JobFormData } from './job.schema';
import type { DynamicField } from '@/types/common.types';
import { useDynamicFields } from '@/modules/dynamic-fields/useDynamicFields';

const { Text } = Typography;

const JOB_TYPE_OPTIONS = [
  { value: 'one_day', label: 'One Day' },
  { value: 'short_term', label: 'Short Term' },
  { value: 'long_term', label: 'Long Term' },
  { value: 'contract', label: 'Contract' },
  { value: 'permanent', label: 'Permanent' },
];

interface EmployerOption {
  value: string;
  label: string;
  status: string;
}

interface JobCreateModalProps {
  open: boolean;
  onClose: () => void;
  onSubmit: (data: Record<string, unknown>) => void;
  loading?: boolean;
}

const EMPTY_VALUES: JobFormData = {
  employer_id: '', title: '', category_id: '', subcategory_id: '',
  business_data: {}, dynamic_field_values: {},
  // start_date_time/end_date_time deliberately start undefined (no Dayjs default) — cast needed
  // since the schema requires a valid Dayjs once submitted, but the field starts empty.
  start_date_time: undefined as never, end_date_time: undefined as never,
  location_address: '',
  latitude: undefined as never, longitude: undefined as never,
  image_uploads: [],
  required_application_fields: { resume: false, education: false, experience: false, skills: false },
  type: 'long_term', openings: 1, status: 'active', is_featured: false, is_urgent: false,
};

/** Validates the current subcategory's dynamic fields against `values` and injects errors via
 * `setError` for anything that fails — their shape is only known at runtime (see
 * DynamicFieldsRenderer), so this can't live in the static zod schema. */
function validateDynamicFields(
  dynamicFields: DynamicField[],
  values: Record<string, unknown>,
  setError: (name: `dynamic_field_values.${string}`, error: { type: string; message: string }) => void,
): boolean {
  let ok = true;
  for (const f of dynamicFields) {
    const value = values[f.id];
    const isEmpty = value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0);
    if (f.is_required && isEmpty) {
      setError(`dynamic_field_values.${f.id}`, { type: 'required', message: `${f.field_label} is required` });
      ok = false;
      continue;
    }
    if (isEmpty) continue;
    if (f.validation_rules?.min_length && typeof value === 'string' && value.length < f.validation_rules.min_length) {
      setError(`dynamic_field_values.${f.id}`, { type: 'minLength', message: `${f.field_label} must be at least ${f.validation_rules.min_length} characters` });
      ok = false;
    }
    if (f.field_type === 'email' && typeof value === 'string' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
      setError(`dynamic_field_values.${f.id}`, { type: 'email', message: `${f.field_label} must be a valid email address` });
      ok = false;
    }
    if (f.field_type === 'url' && typeof value === 'string' && !/^https?:\/\/.+/.test(value)) {
      setError(`dynamic_field_values.${f.id}`, { type: 'url', message: `${f.field_label} must be a valid URL` });
      ok = false;
    }
  }
  return ok;
}

export function JobCreateModal({ open, onClose, onSubmit, loading }: JobCreateModalProps) {
  const [employers, setEmployers] = useState<EmployerOption[]>([]);
  const [employersLoading, setEmployersLoading] = useState(false);

  const { control, handleSubmit, reset, setValue, getValues, setError, watch } = useForm<JobFormData>({
    resolver: zodResolver(jobFormSchema),
    defaultValues: EMPTY_VALUES,
  });

  const subcategoryId = watch('subcategory_id');
  const { fields: dynamicFields } = useDynamicFields(subcategoryId || null);

  useEffect(() => {
    if (!open) return;
    setEmployersLoading(true);
    employersApi.getAll({ limit: 500 })
      .then((res) => {
        setEmployers(res.data.map((e) => ({ value: e.id, label: e.company_name, status: e.status })));
      })
      .catch(() => {})
      .finally(() => setEmployersLoading(false));
  }, [open]);

  const handleClose = () => {
    onClose();
    reset(EMPTY_VALUES);
  };

  const handleFormSubmit = (values: JobFormData) => {
    if (!validateDynamicFields(dynamicFields, values.dynamic_field_values, setError)) return;

    const businessData = values.business_data ?? {};
    const fmt = (v: unknown): string | undefined => {
      const d = v as { toISOString?: () => string } | undefined;
      return d && typeof d.toISOString === 'function' ? d.toISOString() : undefined;
    };

    const uploads = values.image_uploads ?? [];
    const dynamicFieldValues = values.dynamic_field_values ?? {};
    const { image_uploads: _imageUploads, dynamic_field_values: _dynamicFieldValues, ...rest } = values;

    const payload: Record<string, unknown> = {
      ...rest,
      business_data: businessData,
      // Only submit values for fields still active on this subcategory — see JobEditModal for why.
      dynamic_field_values: Object.entries(dynamicFieldValues)
        .map(([dynamic_field_id, value]) => ({
          dynamic_field_id,
          field: dynamicFields.find((f) => f.id === dynamic_field_id),
          value,
        }))
        .filter((f): f is typeof f & { field: DynamicField } => !!f.field)
        .map(({ dynamic_field_id, field, value }) => ({
          dynamic_field_id,
          value: extractDynamicFieldValue(value, field.field_type),
        }))
        .filter(({ value }) => value !== undefined && value !== null && value !== ''),
      salary: businessData['salary'] != null ? String(businessData['salary']) : undefined,
      start_date_time: fmt(values.start_date_time),
      end_date_time: fmt(values.end_date_time),
      images: (uploads as UploadResult[]).map((u) => u.key),
    };
    onSubmit(payload);
  };

  return (
    <FormDrawer
      title="Create Job Posting"
      subtitle="Post a job on behalf of an employer"
      open={open}
      onClose={handleClose}
      onSubmit={handleSubmit(handleFormSubmit)}
      loading={loading}
      submitLabel="Create Job"
      size="large"
    >
      <Form layout="vertical" component="div">
        {/* ── Employer ────────────────────────────────────────────── */}
        <Divider orientation="left" orientationMargin={0} style={{ marginTop: 0 }}>
          <Text style={{ fontSize: 12, color: '#64748b', margin: 0 }}>Employer</Text>
        </Divider>

        <AppSelect<JobFormData>
          name="employer_id"
          control={control}
          label="Select Employer"
          required
          showSearch
          allowClear
          placeholder={employersLoading ? 'Loading employers...' : 'Search by company name...'}
          notFoundContent={employersLoading ? <Spin size="small" /> : 'No employers found'}
          filterOption={(input, opt) => String(opt?.label ?? '').toLowerCase().includes(input.toLowerCase())}
          optionRender={(opt) => {
            const item = employers.find((e) => e.value === opt.value);
            return (
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontSize: 12 }}>{opt.label}</span>
                {item && (
                  <span style={{
                    fontSize: 10, padding: '1px 6px', borderRadius: 4,
                    background: item.status === 'active' ? '#dcfce7' : '#fef3c7',
                    color: item.status === 'active' ? '#16a34a' : '#92400e',
                  }}>
                    {item.status}
                  </span>
                )}
              </div>
            );
          }}
          options={employers.map((e) => ({ value: e.value, label: e.label }))}
        />

        <JobDynamicFormSections control={control} setValue={setValue} getValues={getValues} />

        {/* ── Admin Settings ──────────────────────────────────────── */}
        <Divider orientation="left" orientationMargin={0}>
          <Text style={{ fontSize: 12, color: '#64748b' }}>Admin Settings</Text>
        </Divider>

        <Row gutter={12}>
          <Col span={8}>
            <AppSelect<JobFormData> name="type" control={control} label="Job Type" options={JOB_TYPE_OPTIONS} />
          </Col>
          <Col span={8}>
            <AppInputNumber<JobFormData> name="openings" control={control} label="Openings" min={1} />
          </Col>
          <Col span={8}>
            <AppSelect<JobFormData>
              name="status"
              control={control}
              label="Initial Status"
              options={[{ value: 'active', label: 'Active' }, { value: 'inactive', label: 'Inactive' }]}
            />
          </Col>
        </Row>

        <Row gutter={12}>
          <Col span={8}>
            <Controller
              name="is_featured"
              control={control}
              render={({ field }) => (
                <Form.Item label="Featured Job">
                  <Switch checkedChildren="Featured" unCheckedChildren="Normal" checked={field.value} onChange={field.onChange} />
                </Form.Item>
              )}
            />
          </Col>
          <Col span={8}>
            <Controller
              name="is_urgent"
              control={control}
              render={({ field }) => (
                <Form.Item label="Urgent Hiring">
                  <Switch checkedChildren="Urgent" unCheckedChildren="Normal" checked={field.value} onChange={field.onChange} />
                </Form.Item>
              )}
            />
          </Col>
        </Row>
      </Form>
    </FormDrawer>
  );
}
