import { AlertCircle, CheckCircle2, FileUp, Loader2, X } from "lucide-react";
import { isValidElement, useId, useRef, useState, type ReactNode } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { normalizePhone } from "@/lib/phone";
import { longLabel } from "@/lib/dates";
import { fmtDate } from "@/lib/format";
import { cn } from "@/lib/utils";

export const selectCls =
  "h-9 w-full rounded-md border bg-card px-2 text-[13.5px] disabled:opacity-60";

/** Label + control + helper + error, with aria wiring. */
export function Field({
  label,
  required,
  error,
  help,
  children,
  className,
}: {
  label: ReactNode;
  required?: boolean;
  error?: string | undefined;
  help?: ReactNode;
  children: ReactNode;
  className?: string;
}) {
  const id = useId();
  // A <label> around several buttons would click the first one, so button groups get role="group" instead.
  const group =
    isValidElement(children) &&
    (typeof children.type !== "string" ? GROUPS.has(children.type) : children.type === "div");
  const Tag = group ? "div" : "label";
  return (
    <Tag
      className={cn("block", className)}
      {...(group ? { role: "group", "aria-labelledby": id } : {})}
    >
      <span id={id} className="text-[13px] font-medium">
        {label}
        {required && <span className="text-danger"> *</span>}
      </span>
      <div className="mt-1">{children}</div>
      {error ? (
        <span role="alert" className="mt-1 flex items-center gap-1 text-[12px] text-danger">
          <AlertCircle className="h-3.5 w-3.5" />
          {error}
        </span>
      ) : help ? (
        <span className="mt-1 block text-[12px] text-muted-foreground">{help}</span>
      ) : null}
    </Tag>
  );
}
export function TextInput({
  value,
  onChange,
  error,
  ...rest
}: { value: string; onChange: (v: string) => void; error?: string | undefined } & Omit<
  React.ComponentProps<typeof Input>,
  "value" | "onChange"
>) {
  return (
    <Input
      value={value}
      onChange={(e) => onChange(e.target.value)}
      aria-invalid={!!error}
      className={cn(error && "border-danger")}
      {...rest}
    />
  );
}
export function Select({
  value,
  onChange,
  options,
  placeholder = "Choose…",
  error,
  disabled,
  ariaLabel,
}: {
  value: string;
  onChange: (v: string) => void;
  options: (string | [string, string])[];
  placeholder?: string;
  error?: string | undefined;
  disabled?: boolean;
  ariaLabel?: string;
}) {
  return (
    <select
      className={cn(selectCls, error && "border-danger")}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      disabled={disabled}
      aria-label={ariaLabel}
      aria-invalid={!!error}
    >
      <option value="">{placeholder}</option>
      {options.map((o) => {
        const [v, l] = Array.isArray(o) ? o : [o, o];
        return (
          <option key={v} value={v}>
            {l}
          </option>
        );
      })}
    </select>
  );
}
/** Yes/No as a radio pair — never a checkbox that could mean "not answered". */
export function YesNo({
  value,
  onChange,
  name,
  error,
}: {
  value: boolean | undefined;
  onChange: (v: boolean) => void;
  name: string;
  error?: string | undefined;
}) {
  return (
    <div
      role="radiogroup"
      className={cn("inline-flex overflow-hidden rounded-md border", error && "border-danger")}
    >
      {(
        [
          [true, "Yes"],
          [false, "No"],
        ] as const
      ).map(([v, l]) => (
        <button
          key={l}
          type="button"
          role="radio"
          aria-checked={value === v}
          name={name}
          onClick={() => onChange(v)}
          className={cn(
            "px-4 py-1.5 text-[13px] font-medium",
            value === v ? "bg-primary text-primary-foreground" : "bg-card hover:bg-surface-2",
          )}
        >
          {l}
        </button>
      ))}
    </div>
  );
}
export function Segmented<T extends string>({
  value,
  onChange,
  options,
}: {
  value: T | undefined;
  onChange: (v: T) => void;
  options: [T, string][];
}) {
  return (
    <div role="radiogroup" className="inline-flex flex-wrap overflow-hidden rounded-md border">
      {options.map(([v, l]) => (
        <button
          key={v}
          type="button"
          role="radio"
          aria-checked={value === v}
          onClick={() => onChange(v)}
          className={cn(
            "px-3 py-1.5 text-[13px] font-medium",
            value === v ? "bg-primary text-primary-foreground" : "bg-card hover:bg-surface-2",
          )}
        >
          {l}
        </button>
      ))}
    </div>
  );
}
export function TextArea({
  value,
  onChange,
  error,
  rows = 3,
  maxLength,
  placeholder,
}: {
  value: string;
  onChange: (v: string) => void;
  error?: string | undefined;
  rows?: number;
  maxLength?: number;
  placeholder?: string;
}) {
  return (
    <div>
      <Textarea
        rows={rows}
        value={value}
        maxLength={maxLength}
        placeholder={placeholder}
        onChange={(e) => onChange(e.target.value)}
        aria-invalid={!!error}
        className={cn(error && "border-danger")}
      />
      {maxLength && (
        <p className="mt-0.5 text-right text-[11px] text-muted-foreground tabular">
          {value.length} / {maxLength}
        </p>
      )}
    </div>
  );
}
export const WEEKDAYS: [number, string][] = [
  [1, "Mon"],
  [2, "Tue"],
  [3, "Wed"],
  [4, "Thu"],
  [5, "Fri"],
  [6, "Sat"],
  [7, "Sun"],
];
export function WeekdayPicker({
  value,
  onChange,
  error,
}: {
  value: number[];
  onChange: (v: number[]) => void;
  error?: string | undefined;
}) {
  return (
    <div
      className={cn("flex flex-wrap gap-1", error && "rounded-md ring-1 ring-danger")}
      role="group"
      aria-label="Session weekdays"
    >
      {WEEKDAYS.map(([d, l]) => {
        const on = value.includes(d);
        return (
          <button
            key={d}
            type="button"
            aria-pressed={on}
            onClick={() => onChange(on ? value.filter((x) => x !== d) : [...value, d].sort())}
            className={cn(
              "h-8 w-11 rounded-md border text-[12.5px] font-medium",
              on
                ? "border-primary bg-primary text-primary-foreground"
                : "bg-card hover:bg-surface-2",
            )}
          >
            {l}
          </button>
        );
      })}
    </div>
  );
}

/** Phone with live normalisation feedback (shared rules: lib/phone.ts). */
export function PhoneInput({
  value,
  onChange,
  error,
}: {
  value: string;
  onChange: (v: string) => void;
  error?: string | undefined;
}) {
  const r = value.trim() ? normalizePhone(value) : undefined;
  return (
    <div>
      <Input
        inputMode="tel"
        placeholder="09xx xx xx xx"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        aria-invalid={!!error || (r && !r.ok)}
        className={cn((error || (r && !r.ok)) && "border-danger")}
      />
      {r &&
        (r.ok ? (
          <span className="mt-1 flex items-center gap-1 text-[12px] text-success">
            <CheckCircle2 className="h-3.5 w-3.5" />
            {r.display}
          </span>
        ) : (
          !error && (
            <span className="mt-1 block text-[12px] text-danger">
              {r.code === "PHONE_SCIENTIFIC_NOTATION"
                ? "This looks like an Excel number (9.11E+08). Type the full number."
                : "Enter an Ethiopian mobile number, e.g. 0911 22 33 44 or 0711 22 33 44."}
            </span>
          )
        ))}
    </div>
  );
}

/** A date with its meaning in words below it, so day and month cannot be confused. */
export function TypedDateInput({
  value,
  onChange,
  error,
}: {
  value: string;
  onChange: (iso: string) => void;
  error?: string | undefined;
}) {
  return (
    <div>
      <Input
        type="date"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        aria-invalid={!!error}
        className={cn(error && "border-danger")}
      />
      {value && (
        <span className="mt-1 block text-[12px] text-muted-foreground">
          ={" "}
          {longLabel(Number(value.slice(0, 4)), Number(value.slice(5, 7)), Number(value.slice(8)))}
        </span>
      )}
    </div>
  );
}

/** Drag-and-drop file picker with type/size validation. */
export function FileDropzone({
  accept,
  maxSizeMb,
  maxFiles,
  multiple,
  files,
  onFiles,
  help,
}: {
  accept: string[];
  maxSizeMb: number;
  maxFiles?: number;
  multiple?: boolean;
  files: File[];
  onFiles: (f: File[]) => void;
  help?: string;
}) {
  const ref = useRef<HTMLInputElement>(null);
  const [over, setOver] = useState(false);
  const [err, setErr] = useState<string>();
  const take = (list: FileList | null) => {
    if (!list) return;
    const arr = [...list];
    const bad =
      accept.length &&
      arr.find((f) => !accept.includes(f.name.split(".").pop()?.toLowerCase() ?? ""));
    if (bad) return setErr(`${bad.name}: allowed types are ${accept.join(", ")}.`);
    const big = arr.find((f) => f.size > maxSizeMb * 1024 * 1024);
    if (big) return setErr(`${big.name} is larger than ${maxSizeMb} MB.`);
    if (multiple && maxFiles && files.length + arr.length > maxFiles)
      return setErr(`Choose at most ${maxFiles} files.`);
    setErr(undefined);
    onFiles(multiple ? [...files, ...arr] : arr.slice(0, 1));
  };
  return (
    <div>
      <button
        type="button"
        onClick={() => ref.current?.click()}
        onDragOver={(e) => {
          e.preventDefault();
          setOver(true);
        }}
        onDragLeave={() => setOver(false)}
        onDrop={(e) => {
          e.preventDefault();
          setOver(false);
          take(e.dataTransfer.files);
        }}
        className={cn(
          "flex w-full flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed px-6 py-8 text-center transition-colors",
          over ? "border-primary bg-primary-soft" : "hover:border-primary/50",
        )}
      >
        <FileUp className="h-7 w-7 text-primary" />
        <span className="font-medium">
          Drop {multiple ? "files" : "a file"} here or click to choose
        </span>
        <span className="text-[12px] text-muted-foreground">
          {help ??
            `${accept.length ? accept.join(", ").toUpperCase() : "Any file type"} · up to ${maxSizeMb} MB${multiple ? " each" : ""}${multiple && maxFiles ? `, at most ${maxFiles} files` : ""}`}
        </span>
      </button>
      <input
        ref={ref}
        type="file"
        className="hidden"
        multiple={multiple}
        accept={accept.map((a) => `.${a}`).join(",") || undefined}
        onChange={(e) => {
          take(e.target.files);
          e.target.value = "";
        }}
      />
      {err && (
        <p role="alert" className="mt-2 text-[12px] text-danger">
          {err}
        </p>
      )}
      {!!files.length && (
        <ul className="mt-2 space-y-1">
          {files.map((f, i) => (
            <li
              key={`${f.name}${i}`}
              className="flex items-center justify-between rounded-md border bg-card px-3 py-1.5 text-[13px]"
            >
              <span className="truncate">
                {f.name}{" "}
                <span className="text-muted-foreground">
                  · {Math.max(1, Math.round(f.size / 1024))} KB
                </span>
              </span>
              <button
                type="button"
                aria-label={`Remove ${f.name}`}
                onClick={() => onFiles(files.filter((_, k) => k !== i))}
              >
                <X className="h-4 w-4" />
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

/** Confirmation dialog; `typeToConfirm` requires typing a word for irreversible actions. */
export function ConfirmDialog({
  open,
  onOpenChange,
  title,
  description,
  confirmLabel,
  destructive,
  typeToConfirm,
  pending,
  disabled,
  onConfirm,
  children,
}: {
  open: boolean;
  onOpenChange: (o: boolean) => void;
  title: string;
  description?: string;
  confirmLabel: string;
  destructive?: boolean;
  typeToConfirm?: string;
  pending?: boolean;
  disabled?: boolean;
  onConfirm: () => void;
  children?: ReactNode;
}) {
  const [typed, setTyped] = useState("");
  return (
    <Dialog
      open={open}
      onOpenChange={(o) => {
        onOpenChange(o);
        if (!o) setTyped("");
      }}
    >
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          {description && <DialogDescription>{description}</DialogDescription>}
        </DialogHeader>
        {children}
        {typeToConfirm && (
          <Field
            label={
              <>
                Type <b>{typeToConfirm}</b> to confirm
              </>
            }
          >
            <Input value={typed} onChange={(e) => setTyped(e.target.value)} />
          </Field>
        )}
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button
            variant={destructive ? "destructive" : "default"}
            disabled={pending || disabled || (!!typeToConfirm && typed !== typeToConfirm)}
            onClick={onConfirm}
          >
            {pending && <Loader2 className="animate-spin" />}
            {confirmLabel}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

/** Before → after table (roster changes, audit). */
export function DiffView({
  before,
  after,
}: {
  before?: Record<string, unknown> | undefined;
  after?: Record<string, unknown> | undefined;
}) {
  const keys = [...new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})])];
  if (!keys.length) return <p className="text-[12.5px] text-muted-foreground">No field changes.</p>;
  return (
    <table className="w-full text-[12.5px]">
      <thead className="text-muted-foreground">
        <tr>
          <th className="py-1 text-left">Field</th>
          <th className="text-left">Before</th>
          <th className="text-left">After</th>
        </tr>
      </thead>
      <tbody>
        {keys.map((k) => (
          <tr key={k} className="border-t">
            <td className="py-1 font-medium">{k}</td>
            <td className="text-danger line-through">{String(before?.[k] ?? "—")}</td>
            <td className="text-success">{String(after?.[k] ?? "—")}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

// Function declarations are hoisted, so this set is complete before any Field renders.
const GROUPS = new Set<unknown>([YesNo, Segmented, WeekdayPicker, FileDropzone, TypedDateInput]);

/** Server error summary above a form (problem+json message + field count). */
export function FormError({ error }: { error: unknown }) {
  if (!error) return null;
  const msg = error instanceof Error ? error.message : "Something went wrong.";
  return (
    <div
      role="alert"
      className="mb-4 flex items-start gap-2 rounded-lg border border-danger/30 bg-danger-soft p-3 text-[13px] text-danger"
    >
      <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" />
      {msg}
    </div>
  );
}
