import { parseSearchTermsInput } from "@client/pages/orchestrator/automatic-run";
import { TokenizedInput } from "@client/pages/orchestrator/TokenizedInput";
import type { JobSourcesValues } from "@client/pages/settings/types";
import type { UpdateSettingsInput } from "@shared/settings-schema.js";
import type React from "react";
import { useState } from "react";
import { Controller, useFormContext } from "react-hook-form";
import {
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Label } from "@/components/ui/label";

type JobSourcesSettingsSectionProps = {
  values: JobSourcesValues;
  isLoading: boolean;
  isSaving: boolean;
};

type TokenizedFieldProps = {
  id: string;
  label: string;
  helperText: string;
  name: keyof Pick<
    UpdateSettingsInput,
    | "ashbyCompanies"
    | "greenhouseCompanies"
    | "leverCompanies"
    | "smartrecruitersCompanies"
    | "teamtailorCompanies"
    | "huntflowTenants"
    | "factorialTenants"
    | "workdayTenants"
    | "careersPageUrls"
    | "icimsTenants"
    | "elutaRssLocations"
  >;
  disabled: boolean;
  defaultValues: string[];
  draft: string;
  onDraftChange: (value: string) => void;
};

function TokenizedCompaniesField({
  id,
  label,
  helperText,
  name,
  disabled,
  defaultValues,
  draft,
  onDraftChange,
}: TokenizedFieldProps) {
  const { control } = useFormContext<UpdateSettingsInput>();

  return (
    <Controller
      name={name}
      control={control}
      render={({ field }) => (
        <div className="space-y-2">
          <Label htmlFor={id}>{label}</Label>
          <TokenizedInput
            id={id}
            values={field.value ?? defaultValues}
            draft={draft}
            parseInput={parseSearchTermsInput}
            onDraftChange={onDraftChange}
            onValuesChange={field.onChange}
            placeholder="Type and press Enter"
            helperText={helperText}
            removeLabelPrefix="Remove"
            disabled={disabled}
          />
        </div>
      )}
    />
  );
}

export const JobSourcesSettingsSection: React.FC<
  JobSourcesSettingsSectionProps
> = ({ values, isLoading, isSaving }) => {
  const disabled = isLoading || isSaving;
  const [ashbyDraft, setAshbyDraft] = useState("");
  const [greenhouseDraft, setGreenhouseDraft] = useState("");
  const [leverDraft, setLeverDraft] = useState("");
  const [smartrecruitersDraft, setSmartrecruitersDraft] = useState("");
  const [teamtailorDraft, setTeamtailorDraft] = useState("");
  const [huntflowDraft, setHuntflowDraft] = useState("");
  const [factorialDraft, setFactorialDraft] = useState("");
  const [workdayDraft, setWorkdayDraft] = useState("");
  const [careersPagesDraft, setCareersPagesDraft] = useState("");
  const [icimsDraft, setIcimsDraft] = useState("");
  const [elutaDraft, setElutaDraft] = useState("");

  return (
    <AccordionItem value="job-sources" className="border rounded-lg px-4">
      <AccordionTrigger className="hover:no-underline py-4">
        <span className="text-base font-semibold">Job sources & ATS</span>
      </AccordionTrigger>
      <AccordionContent className="pb-4 space-y-6">
        <p className="text-sm text-muted-foreground">
          Configure company slugs, tenant IDs, and career-page URLs so ATS and
          direct employer sources appear in the pipeline run dialog. Public job
          boards (Working Nomads, TestDevJobs, Wellfound, Google Jobs, etc.)
          need no setup here.
        </p>

        <div className="space-y-4">
          <div className="text-sm font-semibold">
            Ashby / Greenhouse / Lever
          </div>
          <TokenizedCompaniesField
            id="ashby-companies"
            label="Ashby company slugs"
            name="ashbyCompanies"
            defaultValues={values.ashbyCompanies.default}
            disabled={disabled}
            draft={ashbyDraft}
            onDraftChange={setAshbyDraft}
            helperText="Board slug from jobs.ashbyhq.com/{slug}, e.g. ramp, linear."
          />
          <TokenizedCompaniesField
            id="greenhouse-companies"
            label="Greenhouse company slugs"
            name="greenhouseCompanies"
            defaultValues={values.greenhouseCompanies.default}
            disabled={disabled}
            draft={greenhouseDraft}
            onDraftChange={setGreenhouseDraft}
            helperText="Board slug from boards.greenhouse.io/{slug}, e.g. stripe."
          />
          <TokenizedCompaniesField
            id="lever-companies"
            label="Lever company slugs"
            name="leverCompanies"
            defaultValues={values.leverCompanies.default}
            disabled={disabled}
            draft={leverDraft}
            onDraftChange={setLeverDraft}
            helperText="Board slug from jobs.lever.co/{slug}, e.g. netflix."
          />
        </div>

        <div className="space-y-4">
          <div className="text-sm font-semibold">Other ATS platforms</div>
          <TokenizedCompaniesField
            id="smartrecruiters-companies"
            label="SmartRecruiters companies"
            name="smartrecruitersCompanies"
            defaultValues={values.smartrecruitersCompanies.default}
            disabled={disabled}
            draft={smartrecruitersDraft}
            onDraftChange={setSmartrecruitersDraft}
            helperText="API path segment from jobs.smartrecruiters.com/{company}/..."
          />
          <TokenizedCompaniesField
            id="teamtailor-companies"
            label="Teamtailor subdomains"
            name="teamtailorCompanies"
            defaultValues={values.teamtailorCompanies.default}
            disabled={disabled}
            draft={teamtailorDraft}
            onDraftChange={setTeamtailorDraft}
            helperText="Subdomain from {slug}.teamtailor.com, e.g. testgorilla."
          />
          <TokenizedCompaniesField
            id="huntflow-tenants"
            label="Huntflow tenants"
            name="huntflowTenants"
            defaultValues={values.huntflowTenants.default}
            disabled={disabled}
            draft={huntflowDraft}
            onDraftChange={setHuntflowDraft}
            helperText="Subdomain from {tenant}.huntflow.io, e.g. apicworld."
          />
          <TokenizedCompaniesField
            id="factorial-tenants"
            label="Factorial tenants"
            name="factorialTenants"
            defaultValues={values.factorialTenants.default}
            disabled={disabled}
            draft={factorialDraft}
            onDraftChange={setFactorialDraft}
            helperText="Subdomain from {tenant}.factorialhr.com, e.g. yourbourse."
          />
          <TokenizedCompaniesField
            id="icims-tenants"
            label="iCIMS tenant hosts"
            name="icimsTenants"
            defaultValues={values.icimsTenants.default}
            disabled={disabled}
            draft={icimsDraft}
            onDraftChange={setIcimsDraft}
            helperText="Hostnames such as careers-example.icims.com."
          />
        </div>

        <div className="space-y-4">
          <div className="text-sm font-semibold">Workday & career pages</div>
          <TokenizedCompaniesField
            id="workday-tenants"
            label="Workday career sites"
            name="workdayTenants"
            defaultValues={values.workdayTenants.default}
            disabled={disabled}
            draft={workdayDraft}
            onDraftChange={setWorkdayDraft}
            helperText="Full Workday career URLs or JSON tenant objects."
          />
          <TokenizedCompaniesField
            id="careers-page-urls"
            label="Career page URLs (auto-detect ATS)"
            name="careersPageUrls"
            defaultValues={values.careersPageUrls.default}
            disabled={disabled}
            draft={careersPagesDraft}
            onDraftChange={setCareersPagesDraft}
            helperText="Company career homepages, e.g. https://sentry.io/careers/ — resolves Ashby, Greenhouse, Lever, etc."
          />
          <TokenizedCompaniesField
            id="eluta-locations"
            label="Eluta RSS locations (Canada)"
            name="elutaRssLocations"
            defaultValues={values.elutaRssLocations.default}
            disabled={disabled}
            draft={elutaDraft}
            onDraftChange={setElutaDraft}
            helperText="Location strings for eluta.ca RSS, e.g. Toronto, ON."
          />
        </div>
      </AccordionContent>
    </AccordionItem>
  );
};
