"use client";

import { useState, useEffect } from "react";
import { X, Plus, Trash2, ChevronUp, ChevronDown } from "lucide-react";
import type { ToolType, ToolConfigField, AppIcon } from "@/lib/types";
import { IconSelector } from "@/components/apps/IconSelector";

// ─── Pre-seeded Templates ────────────────────────────────────────────

interface TypeTemplate {
  label: string;
  icon: AppIcon;
  description: string;
  configFields: ToolConfigField[];
}

const TYPE_TEMPLATES: Record<string, TypeTemplate> = {
  nas: {
    label: "NAS",
    icon: { type: "lucide", value: "HardDrive" },
    description: "Network Attached Storage device",
    configFields: [
      { key: "protocol", label: "Protocol", type: "select", options: ["SMB", "NFS", "iSCSI"], required: true },
      { key: "sharePaths", label: "Share Paths", type: "textarea", placeholder: "/share1, /share2" },
      { key: "username", label: "Username", type: "text" },
      { key: "password", label: "Password", type: "password" },
    ],
  },
  camera: {
    label: "Camera",
    icon: { type: "lucide", value: "Camera" },
    description: "Network camera or security camera",
    configFields: [
      { key: "streamUrl", label: "Stream URL", type: "text", placeholder: "rtsp://..." },
      { key: "protocol", label: "Protocol", type: "select", options: ["RTSP", "HTTP", "ONVIF"], required: true },
      { key: "resolution", label: "Resolution", type: "text", placeholder: "1920x1080" },
      { key: "username", label: "Username", type: "text" },
      { key: "password", label: "Password", type: "password" },
    ],
  },
  entertainment: {
    label: "Entertainment",
    icon: { type: "lucide", value: "Tv" },
    description: "Home entertainment equipment",
    configFields: [
      { key: "deviceType", label: "Device Type", type: "select", options: ["TV", "Receiver", "Speaker", "Streaming"] },
      { key: "protocol", label: "Protocol", type: "select", options: ["HDMI-CEC", "IR", "IP"] },
      { key: "model", label: "Model", type: "text" },
    ],
  },
  sensor: {
    label: "Sensor / IoT",
    icon: { type: "lucide", value: "Thermometer" },
    description: "Sensor or IoT device",
    configFields: [
      { key: "sensorType", label: "Sensor Type", type: "select", options: ["Temperature", "Humidity", "Motion", "Light", "Other"] },
      { key: "dataEndpoint", label: "Data Endpoint", type: "text", placeholder: "http://..." },
      { key: "updateInterval", label: "Update Interval", type: "text", placeholder: "e.g. 30s, 5m" },
    ],
  },
  bluetooth: {
    label: "Bluetooth",
    icon: { type: "lucide", value: "Bluetooth" },
    description: "Bluetooth device",
    configFields: [
      { key: "deviceClass", label: "Device Class", type: "select", options: ["Audio", "Input", "Sensor", "Other"] },
      { key: "macAddress", label: "MAC Address", type: "text", placeholder: "AA:BB:CC:DD:EE:FF" },
      { key: "pairingKey", label: "Pairing Key", type: "password" },
    ],
  },
  blank: {
    label: "Blank",
    icon: { type: "lucide", value: "Wrench" },
    description: "",
    configFields: [],
  },
};

// ─── Config Field Editor ─────────────────────────────────────────────

const FIELD_TYPES: ToolConfigField["type"][] = ["text", "select", "number", "password", "textarea"];

function ConfigFieldRow({
  field,
  index,
  total,
  onChange,
  onRemove,
  onMoveUp,
  onMoveDown,
}: {
  field: ToolConfigField;
  index: number;
  total: number;
  onChange: (updated: ToolConfigField) => void;
  onRemove: () => void;
  onMoveUp: () => void;
  onMoveDown: () => void;
}) {
  const inputClass =
    "w-full rounded-lg border border-zinc-200 px-2 py-1.5 text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100";

  return (
    <div className="flex items-start gap-2 rounded-lg border border-zinc-200 p-3 dark:border-zinc-700">
      {/* Move buttons */}
      <div className="flex flex-col gap-0.5 pt-1">
        <button
          type="button"
          onClick={onMoveUp}
          disabled={index === 0}
          className="text-zinc-400 hover:text-zinc-600 disabled:opacity-30 dark:hover:text-zinc-300"
        >
          <ChevronUp size={14} />
        </button>
        <button
          type="button"
          onClick={onMoveDown}
          disabled={index === total - 1}
          className="text-zinc-400 hover:text-zinc-600 disabled:opacity-30 dark:hover:text-zinc-300"
        >
          <ChevronDown size={14} />
        </button>
      </div>

      {/* Field config */}
      <div className="flex-1 space-y-2">
        <div className="flex gap-2">
          <input
            value={field.label}
            onChange={(e) => {
              const label = e.target.value;
              const key = label.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, "");
              onChange({ ...field, label, key: key || field.key });
            }}
            className={inputClass}
            placeholder="Field label"
          />
          <select
            value={field.type}
            onChange={(e) => onChange({ ...field, type: e.target.value as ToolConfigField["type"] })}
            className={inputClass + " w-32 shrink-0"}
          >
            {FIELD_TYPES.map((t) => (
              <option key={t} value={t}>{t}</option>
            ))}
          </select>
        </div>
        {field.type === "select" && (
          <input
            value={(field.options || []).join(", ")}
            onChange={(e) =>
              onChange({ ...field, options: e.target.value.split(",").map((s) => s.trim()).filter(Boolean) })
            }
            className={inputClass}
            placeholder="Options (comma-separated)"
          />
        )}
        <div className="flex gap-2">
          <input
            value={field.placeholder || ""}
            onChange={(e) => onChange({ ...field, placeholder: e.target.value || undefined })}
            className={inputClass}
            placeholder="Placeholder text (optional)"
          />
          <label className="flex shrink-0 items-center gap-1.5 text-xs text-zinc-500">
            <input
              type="checkbox"
              checked={field.required || false}
              onChange={(e) => onChange({ ...field, required: e.target.checked })}
              className="rounded"
            />
            Required
          </label>
        </div>
      </div>

      {/* Remove button */}
      <button
        type="button"
        onClick={onRemove}
        className="mt-1 text-zinc-400 hover:text-red-500"
      >
        <Trash2 size={14} />
      </button>
    </div>
  );
}

// ─── Main Modal ──────────────────────────────────────────────────────

interface ToolTypeModalProps {
  open: boolean;
  onClose: () => void;
  onSave: (data: {
    name: string;
    description?: string;
    icon: AppIcon;
    configFields: ToolConfigField[];
  }) => void;
  editType?: ToolType | null;
  editConfigFields?: ToolConfigField[];
}

export function ToolTypeModal({
  open,
  onClose,
  onSave,
  editType,
  editConfigFields,
}: ToolTypeModalProps) {
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [icon, setIcon] = useState<AppIcon>({ type: "lucide", value: "Wrench" });
  const [configFields, setConfigFields] = useState<ToolConfigField[]>([]);
  const [selectedTemplate, setSelectedTemplate] = useState("");

  useEffect(() => {
    if (open) {
      if (editType) {
        setName(editType.name);
        setDescription(editType.description ?? "");
        setIcon(editType.icon);
        setConfigFields(editConfigFields ? [...editConfigFields] : []);
        setSelectedTemplate("");
      } else {
        setName("");
        setDescription("");
        setIcon({ type: "lucide", value: "Wrench" });
        setConfigFields([]);
        setSelectedTemplate("");
      }
    }
  }, [open, editType, editConfigFields]);

  if (!open) return null;

  const handleTemplateSelect = (templateKey: string) => {
    setSelectedTemplate(templateKey);
    if (templateKey && TYPE_TEMPLATES[templateKey]) {
      const template = TYPE_TEMPLATES[templateKey];
      if (!editType) {
        setName(template.label);
        setDescription(template.description);
        setIcon(template.icon);
      }
      setConfigFields([...template.configFields]);
    }
  };

  const handleFieldChange = (index: number, updated: ToolConfigField) => {
    const next = [...configFields];
    next[index] = updated;
    setConfigFields(next);
  };

  const handleFieldRemove = (index: number) => {
    setConfigFields(configFields.filter((_, i) => i !== index));
  };

  const handleFieldMove = (from: number, to: number) => {
    if (to < 0 || to >= configFields.length) return;
    const next = [...configFields];
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    setConfigFields(next);
  };

  const handleAddField = () => {
    setConfigFields([
      ...configFields,
      { key: "", label: "", type: "text" },
    ]);
  };

  const handleSave = () => {
    if (!name.trim()) return;
    const validFields = configFields.filter((f) => f.label.trim() && f.key.trim());
    onSave({
      name: name.trim(),
      description: description.trim() || undefined,
      icon,
      configFields: validFields,
    });
  };

  const inputClass =
    "w-full rounded-lg border border-zinc-200 px-3 py-2 text-sm dark:border-zinc-700 dark:bg-zinc-800 dark:text-zinc-100";
  const labelClass = "mb-1 block text-xs font-medium text-zinc-500";

  // Dummy upload handler (tools don't need icon uploads but IconSelector requires it)
  const handleUpload = async () => "";

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="w-full max-w-lg max-h-[90vh] overflow-y-auto rounded-2xl bg-white p-6 shadow-xl dark:bg-zinc-900">
        {/* Header */}
        <div className="mb-4 flex items-center justify-between">
          <h3 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
            {editType ? "Edit Type" : "Add Type"}
          </h3>
          <button
            onClick={onClose}
            className="text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300"
          >
            <X size={20} />
          </button>
        </div>

        <div className="space-y-4">
          {/* Template picker (only on create) */}
          {!editType && (
            <div>
              <label className={labelClass}>Start from Template</label>
              <select
                value={selectedTemplate}
                onChange={(e) => handleTemplateSelect(e.target.value)}
                className={inputClass}
              >
                <option value="">Choose a template...</option>
                {Object.entries(TYPE_TEMPLATES).map(([key, tmpl]) => (
                  <option key={key} value={key}>{tmpl.label}</option>
                ))}
              </select>
            </div>
          )}

          {/* Name */}
          <div>
            <label className={labelClass}>Name *</label>
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              className={inputClass}
              placeholder="e.g. NAS, Camera, Entertainment"
            />
          </div>

          {/* Description */}
          <div>
            <label className={labelClass}>Description</label>
            <input
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className={inputClass}
              placeholder="Short description (optional)"
            />
          </div>

          {/* Icon */}
          <div>
            <label className={labelClass}>Icon</label>
            <IconSelector value={icon} onChange={setIcon} onUpload={handleUpload} />
          </div>

          {/* Config Fields */}
          <div>
            <label className={labelClass}>Config Fields</label>
            <p className="mb-2 text-xs text-zinc-400">
              Define the configuration fields for tools of this type.
            </p>
            <div className="space-y-2">
              {configFields.map((field, i) => (
                <ConfigFieldRow
                  key={i}
                  field={field}
                  index={i}
                  total={configFields.length}
                  onChange={(updated) => handleFieldChange(i, updated)}
                  onRemove={() => handleFieldRemove(i)}
                  onMoveUp={() => handleFieldMove(i, i - 1)}
                  onMoveDown={() => handleFieldMove(i, i + 1)}
                />
              ))}
            </div>
            <button
              type="button"
              onClick={handleAddField}
              className="mt-2 flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-950/30"
            >
              <Plus size={14} />
              Add Field
            </button>
          </div>
        </div>

        {/* Footer */}
        <div className="mt-6 flex justify-end gap-2">
          <button
            onClick={onClose}
            className="rounded-lg px-4 py-2 text-sm text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={!name.trim()}
            className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
          >
            {editType ? "Save Changes" : "Create Type"}
          </button>
        </div>
      </div>
    </div>
  );
}
