import { Field, Segmented, Select, TextInput } from "@/components/pbps/form";
import { Input } from "@/components/ui/input";

type D = Record<string, string>;
/** The columns of the employment placement file, in words. */
export const SUPPORT: [string, string][] = [
  ["placement_support_outreach_referrals", "Outreach and referrals"],
  ["placement_support_job_fair", "Job fair"],
  ["placement_support_interview_prep", "Interview preparation"],
  ["placement_support_cv_writing", "CV writing"],
  ["placement_support_direct_placement", "Direct placement"],
  ["placement_support_job_matching", "Job matching"],
  ["placement_support_employer_followup", "Employer follow-up"],
];
const TYPE: [string, string][] = [
  ["wage_employed", "Wage employed"],
  ["self_employed_business", "Self-employed, business"],
  ["self_employed_freelance", "Self-employed, freelance"],
  ["other", "Other"],
];
const CONTRACT: [string, string][] = [
  ["full_time_permanent", "Full time, permanent"],
  ["contract_under_12_months", "Contract under 12 months"],
  ["contract_12_months_or_more", "Contract of 12 months or more"],
  ["other", "Other"],
];
const LEGAL: [string, string][] = [
  ["sole_proprietorship", "Sole proprietorship"],
  ["partnership", "Partnership"],
  ["plc", "Private limited company"],
  ["no_legal_form", "No legal form"],
  ["other", "Other"],
];
const JOB = [
  "employment_type",
  "employment_type_other_text",
  "job_title",
  "employment_start_date",
  "monthly_income_etb",
  "contract_type",
  "contract_type_other_text",
  "employer_name",
  "employer_contact_person",
  "employer_contact_position",
  "employer_email",
  "employer_phone",
  "legal_form",
  "legal_form_other_text",
  "has_business_license",
];
const without = (d: D, keys: string[]): D =>
  Object.fromEntries(Object.entries(d).filter(([k]) => !keys.includes(k)));
/** "Not employed" leaves no job answers behind. */
export const clearJob = (d: D = {}): D => without(d, JOB);
/** What is still missing. The server checks every rule again. */
export function placementProblem(
  value: "yes" | "no" | undefined,
  d: D = {},
  support = true,
): string | undefined {
  if (support && SUPPORT.some(([k]) => !d[k])) return "Answer the seven support questions.";
  if (value !== "yes") return undefined;
  const t = d["employment_type"];
  if (!t) return "Choose the type of employment.";
  const need = [
    "employment_start_date",
    "monthly_income_etb",
    ...(t === "wage_employed"
      ? ["job_title", "contract_type", "employer_name", "employer_contact_person"]
      : []),
    ...(t.startsWith("self") ? ["legal_form", "has_business_license"] : []),
    ...(t === "other" ? ["employment_type_other_text"] : []),
    ...(d["contract_type"] === "other" ? ["contract_type_other_text"] : []),
    ...(d["legal_form"] === "other" ? ["legal_form_other_text"] : []),
  ];
  if (need.some((k) => !d[k])) return "Fill in the required employment details.";
  if (t === "wage_employed" && !d["employer_email"] && !d["employer_phone"])
    return "Give the employer's email or phone.";
  return undefined;
}
export function PlacementFields({
  value,
  d,
  onChange,
}: {
  value: "yes" | "no";
  d: D;
  onChange: (d: D) => void;
}) {
  const set = (k: string, v: string) => onChange({ ...d, [k]: v });
  const t = d["employment_type"] ?? "";
  const self = t.startsWith("self");
  const text = (k: string, label: string, required = false, type = "text") => (
    <Field label={label} required={required}>
      <TextInput type={type} value={d[k] ?? ""} onChange={(v) => set(k, v)} maxLength={500} />
    </Field>
  );
  const yn = (k: string, label: string) => (
    <Field key={k} label={label} required>
      <Segmented
        value={(d[k] as "yes" | "no" | undefined) ?? undefined}
        onChange={(v) => set(k, v)}
        options={[
          ["yes", "Yes"],
          ["no", "No"],
        ]}
      />
    </Field>
  );
  return (
    <details className="mt-3 rounded-lg border bg-surface-2/40 p-3" open>
      <summary className="cursor-pointer text-[13px] font-medium">
        Placement support{value === "yes" && " and employment"}
      </summary>
      <div className="mt-3 grid gap-3 sm:grid-cols-3 lg:grid-cols-4">
        {SUPPORT.map(([k, l]) => yn(k, l))}
        {value === "yes" && (
          <>
            <Field label="Type of employment" required>
              <Select
                value={t}
                onChange={(v) =>
                  // Answers that do not belong to the new type are removed, so nothing contradicts it.
                  onChange({
                    ...clearJob(d),
                    employment_type: v,
                    ...(d["employment_start_date"]
                      ? { employment_start_date: d["employment_start_date"] }
                      : {}),
                    ...(d["monthly_income_etb"]
                      ? { monthly_income_etb: d["monthly_income_etb"] }
                      : {}),
                  })
                }
                options={TYPE}
              />
            </Field>
            {t === "other" && text("employment_type_other_text", "Which employment?", true)}
            {t && (
              <>
                {text("job_title", "Job title or position", t === "wage_employed")}
                <Field label="Started on" required>
                  <Input
                    type="date"
                    value={d["employment_start_date"] ?? ""}
                    onChange={(e) => set("employment_start_date", e.target.value)}
                  />
                </Field>
                {text("monthly_income_etb", "Monthly income, after deductions (ETB)", true)}
              </>
            )}
            {t === "wage_employed" && (
              <>
                <Field label="Contract" required>
                  <Select
                    value={d["contract_type"] ?? ""}
                    onChange={(v) =>
                      onChange({ ...without(d, ["contract_type_other_text"]), contract_type: v })
                    }
                    options={CONTRACT}
                  />
                </Field>
                {d["contract_type"] === "other" &&
                  text("contract_type_other_text", "Which contract?", true)}
                {text("employer_name", "Employer", true)}
                {text("employer_contact_person", "Contact person", true)}
                {text("employer_contact_position", "Position of the contact")}
                {text("employer_email", "Employer email (or phone)")}
                {text("employer_phone", "Employer phone (or email)")}
              </>
            )}
            {self && (
              <>
                <Field label="Legal form" required>
                  <Select
                    value={d["legal_form"] ?? ""}
                    onChange={(v) =>
                      onChange({ ...without(d, ["legal_form_other_text"]), legal_form: v })
                    }
                    options={LEGAL}
                  />
                </Field>
                {d["legal_form"] === "other" &&
                  text("legal_form_other_text", "Which legal form?", true)}
                {yn("has_business_license", "Business licence")}
              </>
            )}
          </>
        )}
        {text("notes", "Notes")}
      </div>
    </details>
  );
}
