import { useEffect, useState } from 'react';

import { Label } from '@/components/ui/label';
import { NativeSelect } from '@/components/ui/native-select';
import { useTenantChildren } from '@/business/scope/queries';
import type { ScopeTier } from '@/business/scope/selectors';
import {
  TENANT_LEVELS,
  levelDepth,
  type ParentLevel,
} from '@/business/tenant-create/selectors';
import { getScopeTierLabel } from '@/business/scope/selectors';

interface TenantParentPickerProps {
  readonly ownTier: ScopeTier;
  readonly targetLevel: ParentLevel;
  readonly onChange: (parentId: string | null) => void;
}

/**
 * Cascading parent selector: walks from the user's own tenant down to
 * `targetLevel` (organization → school → campus), one dropdown per intermediate
 * level. The id selected at `targetLevel` is reported via `onChange`. Bounded to
 * three levels (the full org → school → campus chain).
 */
export function TenantParentPicker({ ownTier, targetLevel, onChange }: TenantParentPickerProps) {
  const ownDepth = levelDepth(ownTier);
  const targetDepth = levelDepth(targetLevel);
  const numSelects = targetDepth - ownDepth;

  const levelA = TENANT_LEVELS[ownDepth];
  const levelB = TENANT_LEVELS[ownDepth + 1];

  const [selA, setSelA] = useState('');
  const [selB, setSelB] = useState('');
  const [selC, setSelC] = useState('');

  const childrenA = useTenantChildren(null, { enabled: numSelects >= 1 });
  const childrenB = useTenantChildren(
    levelA && selA ? { level: levelA, id: selA } : null,
    { enabled: numSelects >= 2 && Boolean(selA) },
  );
  const childrenC = useTenantChildren(
    levelB && selB ? { level: levelB, id: selB } : null,
    { enabled: numSelects >= 3 && Boolean(selB) },
  );

  const parentId = numSelects >= 3 ? selC : numSelects >= 2 ? selB : selA;

  useEffect(() => {
    onChange(parentId || null);
  }, [parentId, onChange]);

  const levels: ParentLevel[] = [];
  for (let i = 0; i < numSelects; i += 1) {
    const level = TENANT_LEVELS[ownDepth + i];
    if (level) levels.push(level);
  }

  const renderSelect = (
    level: ParentLevel,
    rows: { id: string; name: string | null }[] | undefined,
    value: string,
    onSelect: (id: string) => void,
    disabled: boolean,
  ) => (
    <div key={level} className="space-y-1.5">
      <Label htmlFor={`parent-${level}`}>{getScopeTierLabel(level)}</Label>
      <NativeSelect
        id={`parent-${level}`}
        value={value}
        disabled={disabled}
        onChange={(event) => onSelect(event.target.value)}
      >
        <option value="">Select {getScopeTierLabel(level).toLowerCase()}…</option>
        {(rows ?? []).map((row) => (
          <option key={row.id} value={row.id}>
            {row.name ?? row.id}
          </option>
        ))}
      </NativeSelect>
    </div>
  );

  return (
    <div className="space-y-4">
      {levels.map((level, index) => {
        if (index === 0) {
          return renderSelect(level, childrenA.data?.rows, selA, (id) => {
            setSelA(id);
            setSelB('');
            setSelC('');
          }, false);
        }
        if (index === 1) {
          return renderSelect(level, childrenB.data?.rows, selB, (id) => {
            setSelB(id);
            setSelC('');
          }, !selA);
        }
        return renderSelect(level, childrenC.data?.rows, selC, setSelC, !selB);
      })}
    </div>
  );
}
