import { TokenizedInput } from "@client/pages/orchestrator/TokenizedInput";
import type { UpdateSettingsInput } from "@shared/settings-schema.js";
import type { JobSearchProfile } from "@shared/types.js";
import { Target, User } from "lucide-react";
import type React from "react";
import { useState } from "react";
import { useFormContext } from "react-hook-form";
import {
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Textarea } from "@/components/ui/textarea";
import { ProfileManager } from "./ProfileManager";

type JobSearchProfileSectionProps = {
  values: {
    effective: JobSearchProfile | null;
    default: JobSearchProfile | null;
  };
  activeProfileId: string | null;
  isLoading: boolean;
  isSaving: boolean;
};

function parseTokens(input: string): string[] {
  return input
    .split(/[\n,]/g)
    .map((v) => v.trim())
    .filter(Boolean);
}

const EMPTY_PROFILE: JobSearchProfile = {
  targetRoles: [],
  experienceLevel: "",
  mustHaveSkills: [],
  niceToHaveSkills: [],
  dealBreakers: [],
  preferredWorkArrangement: [],
  preferredLocations: [],
  minimumSalary: "",
  industriesToTarget: [],
  industriesToAvoid: [],
  aboutMe: "",
};

const EXPERIENCE_LEVELS = [
  { value: "", label: "Not specified" },
  { value: "intern", label: "Intern / Placement" },
  { value: "graduate", label: "Graduate / Entry-level" },
  { value: "junior", label: "Junior (0-2 years)" },
  { value: "mid", label: "Mid-level (2-5 years)" },
  { value: "senior", label: "Senior (5+ years)" },
  { value: "lead", label: "Lead / Principal" },
];

const WORK_ARRANGEMENTS = [
  { value: "remote", label: "Remote" },
  { value: "hybrid", label: "Hybrid" },
  { value: "onsite", label: "On-site" },
];

export const JobSearchProfileSection: React.FC<
  JobSearchProfileSectionProps
> = ({ values, activeProfileId, isLoading, isSaving }) => {
  const { watch, setValue } = useFormContext<UpdateSettingsInput>();
  const [targetRoleDraft, setTargetRoleDraft] = useState("");
  const [mustHaveSkillDraft, setMustHaveSkillDraft] = useState("");
  const [niceToHaveSkillDraft, setNiceToHaveSkillDraft] = useState("");
  const [dealBreakerDraft, setDealBreakerDraft] = useState("");
  const [locationDraft, setLocationDraft] = useState("");
  const [targetIndustryDraft, setTargetIndustryDraft] = useState("");
  const [avoidIndustryDraft, setAvoidIndustryDraft] = useState("");

  const current: JobSearchProfile =
    watch("jobSearchProfile") ?? values.effective ?? EMPTY_PROFILE;

  const updateField = <K extends keyof JobSearchProfile>(
    key: K,
    val: JobSearchProfile[K],
  ) => {
    setValue(
      "jobSearchProfile",
      { ...current, [key]: val },
      { shouldDirty: true },
    );
  };

  return (
    <AccordionItem value="jobSearchProfile" className="border rounded-lg px-4">
      <AccordionTrigger className="hover:no-underline py-4">
        <span className="text-base font-semibold flex items-center gap-2">
          <User className="h-4 w-4" />
          Job Search Profile
        </span>
      </AccordionTrigger>
      <AccordionContent className="pb-4">
        <ProfileManager
          activeProfileId={activeProfileId}
          disabled={isLoading || isSaving}
        />
        <div className="space-y-4">
          <p className="text-xs text-muted-foreground">
            Tell the AI what kind of jobs you're looking for. This dramatically
            improves scoring accuracy — a Full Stack Dev job won't score high if
            you're an Automation Tester.
          </p>

          {/* About Me */}
          <div className="space-y-2">
            <label
              htmlFor="about-me"
              className="text-sm font-medium leading-none"
            >
              About You & What You're Looking For
            </label>
            <Textarea
              id="about-me"
              value={current.aboutMe}
              onChange={(e) => updateField("aboutMe", e.target.value)}
              placeholder="I'm a QA automation engineer with 2 years experience in Playwright and Cypress. Looking for SDET or automation tester roles, preferably at product companies. Not interested in manual QA or full-stack development."
              disabled={isLoading || isSaving}
              maxLength={4000}
              rows={4}
            />
            <p className="text-xs text-muted-foreground">
              Free-form description of who you are and what you want. This gives
              the AI scorer the most context.
            </p>
          </div>

          <Separator />

          {/* Target Roles */}
          <div className="space-y-2">
            <label
              htmlFor="target-roles"
              className="text-sm font-medium leading-none flex items-center gap-1.5"
            >
              <Target className="h-3.5 w-3.5" />
              Target Role Titles
            </label>
            <TokenizedInput
              id="target-roles"
              values={current.targetRoles}
              draft={targetRoleDraft}
              parseInput={parseTokens}
              onDraftChange={setTargetRoleDraft}
              onValuesChange={(vals) => updateField("targetRoles", vals)}
              placeholder='e.g. "Automation Tester", "SDET", "QA Engineer"'
              helperText="The kinds of roles you actually want. Jobs matching these titles score much higher."
              removeLabelPrefix="Remove role"
              disabled={isLoading || isSaving}
            />
          </div>

          {/* Experience Level */}
          <div className="space-y-2">
            <label
              htmlFor="experience-level"
              className="text-sm font-medium leading-none"
            >
              Experience Level
            </label>
            <select
              id="experience-level"
              className="flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
              value={current.experienceLevel}
              onChange={(e) => updateField("experienceLevel", e.target.value)}
              disabled={isLoading || isSaving}
            >
              {EXPERIENCE_LEVELS.map((lvl) => (
                <option key={lvl.value} value={lvl.value}>
                  {lvl.label}
                </option>
              ))}
            </select>
          </div>

          <Separator />

          {/* Must-Have Skills */}
          <div className="space-y-2">
            <label
              htmlFor="must-have-skills"
              className="text-sm font-medium leading-none"
            >
              Must-Have Skills
            </label>
            <TokenizedInput
              id="must-have-skills"
              values={current.mustHaveSkills}
              draft={mustHaveSkillDraft}
              parseInput={parseTokens}
              onDraftChange={setMustHaveSkillDraft}
              onValuesChange={(vals) => updateField("mustHaveSkills", vals)}
              placeholder='e.g. "Playwright", "TypeScript", "CI/CD"'
              helperText="Skills you consider essential. Jobs missing these will score lower."
              removeLabelPrefix="Remove skill"
              disabled={isLoading || isSaving}
            />
          </div>

          {/* Nice-to-Have Skills */}
          <div className="space-y-2">
            <label
              htmlFor="nice-to-have-skills"
              className="text-sm font-medium leading-none"
            >
              Nice-to-Have Skills
            </label>
            <TokenizedInput
              id="nice-to-have-skills"
              values={current.niceToHaveSkills}
              draft={niceToHaveSkillDraft}
              parseInput={parseTokens}
              onDraftChange={setNiceToHaveSkillDraft}
              onValuesChange={(vals) => updateField("niceToHaveSkills", vals)}
              placeholder='e.g. "Docker", "AWS", "Python"'
              helperText="Bonus skills. Jobs with these get a small boost."
              removeLabelPrefix="Remove skill"
              disabled={isLoading || isSaving}
            />
          </div>

          <Separator />

          {/* Deal-Breakers */}
          <div className="space-y-2">
            <label
              htmlFor="deal-breakers"
              className="text-sm font-medium leading-none text-destructive"
            >
              Deal-Breakers
            </label>
            <TokenizedInput
              id="deal-breakers"
              values={current.dealBreakers}
              draft={dealBreakerDraft}
              parseInput={parseTokens}
              onDraftChange={setDealBreakerDraft}
              onValuesChange={(vals) => updateField("dealBreakers", vals)}
              placeholder='e.g. "sales engineering", "10+ years required", "unpaid"'
              helperText="If a job matches these, it gets scored 0-15 regardless of other factors."
              removeLabelPrefix="Remove deal-breaker"
              disabled={isLoading || isSaving}
            />
          </div>

          <Separator />

          {/* Work Arrangement */}
          <div className="space-y-2">
            <label
              htmlFor="work-arrangement"
              className="text-sm font-medium leading-none"
            >
              Preferred Work Arrangement
            </label>
            <div className="flex flex-wrap gap-2">
              {WORK_ARRANGEMENTS.map((wa) => {
                const isSelected = current.preferredWorkArrangement.includes(
                  wa.value,
                );
                return (
                  <button
                    key={wa.value}
                    type="button"
                    className={`inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
                      isSelected
                        ? "border-primary bg-primary/10 text-primary"
                        : "border-border bg-background text-muted-foreground hover:bg-muted"
                    }`}
                    onClick={() => {
                      const next = isSelected
                        ? current.preferredWorkArrangement.filter(
                            (v) => v !== wa.value,
                          )
                        : [...current.preferredWorkArrangement, wa.value];
                      updateField("preferredWorkArrangement", next);
                    }}
                    disabled={isLoading || isSaving}
                  >
                    {wa.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Preferred Locations */}
          <div className="space-y-2">
            <label
              htmlFor="preferred-locations"
              className="text-sm font-medium leading-none"
            >
              Preferred Locations
            </label>
            <TokenizedInput
              id="preferred-locations"
              values={current.preferredLocations}
              draft={locationDraft}
              parseInput={parseTokens}
              onDraftChange={setLocationDraft}
              onValuesChange={(vals) => updateField("preferredLocations", vals)}
              placeholder='e.g. "London", "Remote UK", "Leeds"'
              helperText="Where you want to work. Leave empty for any location."
              removeLabelPrefix="Remove location"
              disabled={isLoading || isSaving}
            />
          </div>

          {/* Minimum Salary */}
          <div className="space-y-2">
            <label
              htmlFor="minimum-salary"
              className="text-sm font-medium leading-none"
            >
              Minimum Salary
            </label>
            <Input
              id="minimum-salary"
              value={current.minimumSalary}
              onChange={(e) => updateField("minimumSalary", e.target.value)}
              placeholder='e.g. "£35,000" or "40000"'
              disabled={isLoading || isSaving}
              maxLength={100}
            />
          </div>

          <Separator />

          {/* Industries to Target */}
          <div className="space-y-2">
            <label
              htmlFor="target-industries"
              className="text-sm font-medium leading-none"
            >
              Target Industries
            </label>
            <TokenizedInput
              id="target-industries"
              values={current.industriesToTarget}
              draft={targetIndustryDraft}
              parseInput={parseTokens}
              onDraftChange={setTargetIndustryDraft}
              onValuesChange={(vals) => updateField("industriesToTarget", vals)}
              placeholder='e.g. "fintech", "healthtech", "SaaS"'
              helperText="Industries you prefer. Leave empty for any."
              removeLabelPrefix="Remove industry"
              disabled={isLoading || isSaving}
            />
          </div>

          {/* Industries to Avoid */}
          <div className="space-y-2">
            <label
              htmlFor="avoid-industries"
              className="text-sm font-medium leading-none"
            >
              Industries to Avoid
            </label>
            <TokenizedInput
              id="avoid-industries"
              values={current.industriesToAvoid}
              draft={avoidIndustryDraft}
              parseInput={parseTokens}
              onDraftChange={setAvoidIndustryDraft}
              onValuesChange={(vals) => updateField("industriesToAvoid", vals)}
              placeholder='e.g. "gambling", "defense", "crypto"'
              helperText="Industries you want to exclude."
              removeLabelPrefix="Remove industry"
              disabled={isLoading || isSaving}
            />
          </div>
        </div>
      </AccordionContent>
    </AccordionItem>
  );
};
