"use client";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";

type FormFieldDef = {
  id: string;
  key: string;
  label: string;
  type: string;
  section: string;
  required: boolean;
  options?: string[] | null;
  placeholder?: string | null;
  helpText?: string | null;
  isCore: boolean;
};

interface DynamicFieldProps {
  field: FormFieldDef;
  value: unknown;
  onChange: (value: unknown) => void;
  readOnly: boolean;
}

export type { FormFieldDef };

export function DynamicField({ field, value, onChange, readOnly }: DynamicFieldProps) {
  const opts = Array.isArray(field.options) ? (field.options as string[]) : [];

  const renderInput = () => {
    switch (field.type) {
      case "text":
      case "email":
      case "phone":
      case "url":
      case "number": {
        const inputType = field.type === "phone" ? "tel" : field.type;
        return (
          <Input
            type={inputType}
            value={String(value ?? "")}
            onChange={(e) =>
              onChange(
                field.type === "number"
                  ? e.target.value === ""
                    ? null
                    : Number(e.target.value)
                  : e.target.value
              )
            }
            readOnly={readOnly}
            placeholder={field.placeholder || undefined}
            className={readOnly ? "opacity-70 cursor-default" : ""}
          />
        );
      }

      case "textarea":
        return (
          <Textarea
            value={String(value ?? "")}
            onChange={(e) => onChange(e.target.value)}
            rows={3}
            readOnly={readOnly}
            placeholder={field.placeholder || undefined}
            className={readOnly ? "opacity-70 cursor-default" : ""}
          />
        );

      case "date":
        return (
          <Input
            type="date"
            value={value ? String(value).slice(0, 10) : ""}
            onChange={(e) => onChange(e.target.value || null)}
            readOnly={readOnly}
            className={readOnly ? "opacity-70 cursor-default" : ""}
          />
        );

      case "select":
      case "radio": {
        if (readOnly) {
          return (
            <Input
              value={value ? String(value) : "—"}
              readOnly
              className="opacity-70 cursor-default"
            />
          );
        }
        return (
          <select
            value={String(value ?? "")}
            onChange={(e) => onChange(e.target.value || null)}
            className="h-8 w-full rounded-lg border border-input bg-transparent px-2.5 py-1 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30"
          >
            <option value="">—</option>
            {opts.map((opt) => (
              <option key={opt} value={opt}>
                {opt}
              </option>
            ))}
          </select>
        );
      }

      case "multiselect": {
        const selected = new Set(
          Array.isArray(value) ? (value as string[]) : []
        );
        const toggle = (opt: string) => {
          if (readOnly) return;
          const next = new Set(selected);
          if (next.has(opt)) next.delete(opt);
          else next.add(opt);
          onChange(Array.from(next));
        };
        return (
          <div className="flex flex-wrap gap-1.5">
            {opts.map((opt) => {
              const isOn = selected.has(opt);
              return (
                <button
                  key={opt}
                  type="button"
                  onClick={() => toggle(opt)}
                  disabled={readOnly}
                  className={cn(
                    "inline-flex items-center rounded-lg border px-2.5 py-1 text-xs font-medium transition-colors",
                    isOn
                      ? "border-primary/40 bg-primary/10 text-primary hover:bg-primary/20"
                      : "border-border bg-muted/30 text-muted-foreground hover:bg-muted/60 hover:text-foreground",
                    readOnly && "cursor-default opacity-70"
                  )}
                >
                  {opt}
                </button>
              );
            })}
          </div>
        );
      }

      case "checkbox":
        return (
          <div className="flex items-center gap-2 pt-1">
            <Checkbox
              checked={Boolean(value)}
              onCheckedChange={
                readOnly ? undefined : (checked: boolean) => onChange(checked)
              }
              disabled={readOnly}
            />
          </div>
        );

      default:
        return (
          <Input
            value={String(value ?? "")}
            onChange={(e) => onChange(e.target.value)}
            readOnly={readOnly}
            placeholder={field.placeholder || undefined}
            className={readOnly ? "opacity-70 cursor-default" : ""}
          />
        );
    }
  };

  return (
    <div className={field.type === "textarea" ? "sm:col-span-2" : ""}>
      <Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
        {field.label}
        {field.required && (
          <span className="text-destructive ml-0.5">*</span>
        )}
      </Label>
      {renderInput()}
      {field.helpText && (
        <p className="mt-1 text-[11px] text-muted-foreground/70">
          {field.helpText}
        </p>
      )}
    </div>
  );
}
