import { GERMAN_FEDERAL_STATES, inferStateFromPostalCode, ResourceType } from "@capakraken/shared";
import { InfoTooltip } from "~/components/ui/InfoTooltip.js";

type CountryOption = { id: string; name: string; metroCities: { id: string; name: string }[] };
type OrgUnitOption = { id: string; name: string; level: number; isActive: boolean };
type ClientOption = { id: string; name: string };
type ManagementGroupOption = { id: string; name: string; levels: { id: string; name: string }[] };

interface ResourceOrgClassificationProps {
  form: {
    postalCode: string;
    federalState: string;
    countryId: string;
    metroCityId: string;
    orgUnitId: string;
    clientUnitId: string;
    managementLevelGroupId: string;
    managementLevelId: string;
    resourceType: string;
    chgResponsibility: boolean;
    rolledOff: boolean;
    departed: boolean;
    enterpriseId: string;
    fte: string;
  };
  onSetField: (key: string, value: string | boolean) => void;
  countryOptions: CountryOption[];
  orgUnitOptions: OrgUnitOption[];
  clientOptions: ClientOption[];
  managementGroupOptions: ManagementGroupOption[];
  inputClass: string;
  labelClass: string;
  sectionHeaderClass: string;
}

export function ResourceOrgClassification({
  form,
  onSetField,
  countryOptions,
  orgUnitOptions,
  clientOptions,
  managementGroupOptions,
  inputClass,
  labelClass,
  sectionHeaderClass,
}: ResourceOrgClassificationProps) {
  const selectedCountry = countryOptions.find((c) => c.id === form.countryId);
  const metroCities = selectedCountry?.metroCities ?? [];
  const selectedGroup = managementGroupOptions.find((g) => g.id === form.managementLevelGroupId);
  const mgmtLevels = selectedGroup?.levels ?? [];

  return (
    <>
      {/* Postal Code & Federal State */}
      <div className="grid grid-cols-2 gap-4 mt-4">
        <div>
          <label className={labelClass} htmlFor="rm-postalCode">
            Postal Code (PLZ){" "}
            <span className="text-gray-400 dark:text-gray-500 font-normal">(optional)</span>
            <InfoTooltip content="German postal code. Used to auto-derive the federal state for public holiday calculations." />
          </label>
          <input
            id="rm-postalCode"
            type="text"
            className={inputClass}
            placeholder="80331"
            maxLength={5}
            value={form.postalCode}
            onChange={(e) => {
              const plz = e.target.value;
              onSetField("postalCode", plz);
              if (/^\d{5}$/.test(plz)) {
                const inferred = inferStateFromPostalCode(plz);
                if (inferred && !form.federalState) {
                  onSetField("federalState", inferred);
                }
              }
            }}
          />
        </div>
        <div>
          <label className={labelClass} htmlFor="rm-federalState">
            Federal State{" "}
            <span className="text-gray-400 dark:text-gray-500 font-normal">(optional)</span>
            <InfoTooltip content="Determines which public holidays apply (e.g. Bavaria has extra holidays). Auto-derived from postal code." />
          </label>
          <select
            id="rm-federalState"
            className={inputClass}
            value={form.federalState}
            onChange={(e) => onSetField("federalState", e.target.value)}
          >
            <option value="">— Not specified —</option>
            {Object.entries(GERMAN_FEDERAL_STATES).map(([abbr, name]) => (
              <option key={abbr} value={abbr}>
                {name} ({abbr})
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Section: Organization & Classification */}
      <p className={sectionHeaderClass}>Organization &amp; Classification</p>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className={labelClass} htmlFor="rm-enterpriseId">
            Enterprise ID{" "}
            <span className="text-gray-400 dark:text-gray-500 font-normal">(optional)</span>
            <InfoTooltip content="Corporate directory ID for cross-system integration (e.g. a.kasperovich)." />
          </label>
          <input
            id="rm-enterpriseId"
            type="text"
            className={inputClass}
            placeholder="a.kasperovich"
            value={form.enterpriseId}
            onChange={(e) => onSetField("enterpriseId", e.target.value)}
          />
        </div>
        <div>
          <label className={labelClass} htmlFor="rm-fte">
            FTE
            <InfoTooltip content="Full-Time Equivalent (0.01-1.0). A value of 0.5 means the resource works 50% of standard hours." />
          </label>
          <input
            id="rm-fte"
            type="number"
            min="0.01"
            max="1"
            step="0.01"
            className={inputClass}
            placeholder="1.0"
            value={form.fte}
            onChange={(e) => onSetField("fte", e.target.value)}
          />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 mt-4">
        <div>
          <label className={labelClass} htmlFor="rm-countryId">
            Country
          </label>
          <select
            id="rm-countryId"
            className={inputClass}
            value={form.countryId}
            onChange={(e) => {
              onSetField("countryId", e.target.value);
              onSetField("metroCityId", "");
            }}
          >
            <option value="">— Not specified —</option>
            {countryOptions.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className={labelClass} htmlFor="rm-metroCityId">
            Metro City
          </label>
          <select
            id="rm-metroCityId"
            className={inputClass}
            value={form.metroCityId}
            onChange={(e) => onSetField("metroCityId", e.target.value)}
            disabled={!form.countryId}
          >
            <option value="">— Not specified —</option>
            {metroCities.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 mt-4">
        <div>
          <label className={labelClass} htmlFor="rm-orgUnitId">
            Org Unit (L7 Team)
          </label>
          <select
            id="rm-orgUnitId"
            className={inputClass}
            value={form.orgUnitId}
            onChange={(e) => onSetField("orgUnitId", e.target.value)}
          >
            <option value="">— Not specified —</option>
            {orgUnitOptions
              .filter((u) => u.level === 7 && u.isActive)
              .map((u) => (
                <option key={u.id} value={u.id}>
                  {u.name}
                </option>
              ))}
          </select>
        </div>
        <div>
          <label className={labelClass} htmlFor="rm-clientUnitId">
            Client Unit
          </label>
          <select
            id="rm-clientUnitId"
            className={inputClass}
            value={form.clientUnitId}
            onChange={(e) => onSetField("clientUnitId", e.target.value)}
          >
            <option value="">— Not specified —</option>
            {clientOptions.map((c) => (
              <option key={c.id} value={c.id}>
                {c.name}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-4 mt-4">
        <div>
          <label className={labelClass} htmlFor="rm-mgmtGroupId">
            Management Level Group
            <InfoTooltip content="Seniority grouping (e.g. Associate, Manager, Director). Determines the available management levels." />
          </label>
          <select
            id="rm-mgmtGroupId"
            className={inputClass}
            value={form.managementLevelGroupId}
            onChange={(e) => {
              onSetField("managementLevelGroupId", e.target.value);
              onSetField("managementLevelId", "");
            }}
          >
            <option value="">— Not specified —</option>
            {managementGroupOptions.map((g) => (
              <option key={g.id} value={g.id}>
                {g.name}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label className={labelClass} htmlFor="rm-mgmtLevelId">
            Management Level
            <InfoTooltip content="Specific seniority level within the group. Used in chargeability reports and cost analysis." />
          </label>
          <select
            id="rm-mgmtLevelId"
            className={inputClass}
            value={form.managementLevelId}
            onChange={(e) => onSetField("managementLevelId", e.target.value)}
            disabled={!form.managementLevelGroupId}
          >
            <option value="">— Not specified —</option>
            {mgmtLevels.map((l) => (
              <option key={l.id} value={l.id}>
                {l.name}
              </option>
            ))}
          </select>
        </div>
      </div>

      <div className="grid grid-cols-4 gap-4 mt-4">
        <div>
          <label className={labelClass} htmlFor="rm-resourceType">
            Resource Type
            <InfoTooltip content="Employee, contractor, or freelancer. Affects cost attribution rules." />
          </label>
          <select
            id="rm-resourceType"
            className={inputClass}
            value={form.resourceType}
            onChange={(e) => onSetField("resourceType", e.target.value)}
          >
            {Object.values(ResourceType).map((t) => (
              <option key={t} value={t}>
                {t.charAt(0) + t.slice(1).toLowerCase()}
              </option>
            ))}
          </select>
        </div>
        <div className="flex items-end pb-2">
          <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
            <input
              type="checkbox"
              checked={form.chgResponsibility}
              onChange={(e) => onSetField("chgResponsibility", e.target.checked)}
              className="rounded border-gray-300 text-brand-600 focus:ring-brand-500"
            />
            Chg Responsibility
          </label>
        </div>
        <div className="flex items-end pb-2">
          <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
            <input
              type="checkbox"
              checked={form.rolledOff}
              onChange={(e) => onSetField("rolledOff", e.target.checked)}
              className="rounded border-gray-300 text-brand-600 focus:ring-brand-500"
            />
            Rolled Off
          </label>
        </div>
        <div className="flex items-end pb-2">
          <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
            <input
              type="checkbox"
              checked={form.departed}
              onChange={(e) => onSetField("departed", e.target.checked)}
              className="rounded border-gray-300 text-brand-600 focus:ring-brand-500"
            />
            Departed
          </label>
        </div>
      </div>
    </>
  );
}
