"use client";

import { useState, useEffect } from "react";
import { X, Trash2, Eye, EyeOff } from "lucide-react";
import type { ToolEntry, ToolType, ToolTypeDefinition, ToolConfigField, AppIcon } from "@/lib/types";
import { IconSelector } from "@/components/apps/IconSelector";

const COLOR_PRESETS = [
  "#6366f1",
  "#ec4899",
  "#8b5cf6",
  "#f59e0b",
  "#10b981",
  "#3b82f6",
  "#ef4444",
  "#14b8a6",
];

// ─── Dynamic Field Renderer ──────────────────────────────────────────

function DynamicField({
  field,
  value,
  onChange,
}: {
  field: ToolConfigField;
  value: string;
  onChange: (val: string) => void;
}) {
  const [showPassword, setShowPassword] = useState(false);
  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";

  if (field.type === "select") {
    return (
      <select value={value} onChange={(e) => onChange(e.target.value)} className={inputClass}>
        <option value="">Select...</option>
        {(field.options || []).map((opt) => (
          <option key={opt} value={opt}>{opt}</option>
        ))}
      </select>
    );
  }

  if (field.type === "textarea") {
    return (
      <textarea
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={inputClass + " min-h-[60px] resize-y"}
        placeholder={field.placeholder}
        rows={3}
      />
    );
  }

  if (field.type === "password") {
    return (
      <div className="relative">
        <input
          type={showPassword ? "text" : "password"}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          className={inputClass + " pr-10"}
          placeholder={field.placeholder}
        />
        <button
          type="button"
          onClick={() => setShowPassword(!showPassword)}
          className="absolute right-2 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300"
        >
          {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
        </button>
      </div>
    );
  }

  return (
    <input
      type={field.type === "number" ? "number" : "text"}
      value={value}
      onChange={(e) => onChange(e.target.value)}
      className={inputClass}
      placeholder={field.placeholder}
    />
  );
}

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

interface ToolModalProps {
  open: boolean;
  onClose: () => void;
  onSave: (data: {
    name: string;
    typeId: string;
    address?: string;
    description?: string;
    icon: AppIcon;
    color: string;
    config: Record<string, string>;
    status: "online" | "offline";
  }) => void;
  onDelete?: () => void;
  editTool?: ToolEntry | null;
  types: ToolType[];
  typeDefinitions: Record<string, ToolTypeDefinition>;
  defaultTypeId?: string;
}

export function ToolModal({
  open,
  onClose,
  onSave,
  onDelete,
  editTool,
  types,
  typeDefinitions,
  defaultTypeId,
}: ToolModalProps) {
  const [name, setName] = useState("");
  const [typeId, setTypeId] = useState("");
  const [address, setAddress] = useState("");
  const [description, setDescription] = useState("");
  const [icon, setIcon] = useState<AppIcon>({ type: "lucide", value: "Wrench" });
  const [color, setColor] = useState(COLOR_PRESETS[0]);
  const [config, setConfig] = useState<Record<string, string>>({});
  const [status, setStatus] = useState<"online" | "offline">("offline");

  useEffect(() => {
    if (open) {
      if (editTool) {
        setName(editTool.name);
        setTypeId(editTool.typeId);
        setAddress(editTool.address ?? "");
        setDescription(editTool.description ?? "");
        setIcon(editTool.icon);
        setColor(editTool.color);
        setConfig({ ...editTool.config });
        setStatus(editTool.status);
      } else {
        setName("");
        setTypeId(defaultTypeId ?? types[0]?.id ?? "");
        setAddress("");
        setDescription("");
        setIcon({ type: "lucide", value: "Wrench" });
        setColor(COLOR_PRESETS[0]);
        setConfig({});
        setStatus("offline");
      }
    }
  }, [open, editTool, types, defaultTypeId]);

  if (!open) return null;

  const currentFields = typeDefinitions[typeId]?.configFields || [];

  const handleConfigChange = (key: string, value: string) => {
    setConfig((prev) => ({ ...prev, [key]: value }));
  };

  const missingRequired = currentFields.filter(f => f.required && !config[f.key]?.trim());

  const handleSave = () => {
    if (!name.trim() || !typeId) return;
    if (missingRequired.length > 0) return;
    onSave({
      name: name.trim(),
      typeId,
      address: address.trim() || undefined,
      description: description.trim() || undefined,
      icon,
      color,
      config,
      status,
    });
  };

  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
  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">
            {editTool ? "Edit Tool" : "Add Tool"}
          </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">
          {/* Name */}
          <div>
            <label className={labelClass}>Name *</label>
            <input
              value={name}
              onChange={(e) => setName(e.target.value)}
              className={inputClass}
              placeholder="My NAS"
            />
          </div>

          {/* Type */}
          <div>
            <label className={labelClass}>Type *</label>
            {editTool ? (
              <input
                value={types.find((t) => t.id === typeId)?.name ?? typeId}
                className={inputClass + " bg-zinc-50 dark:bg-zinc-800/50"}
                readOnly
              />
            ) : (
              <select
                value={typeId}
                onChange={(e) => {
                  setTypeId(e.target.value);
                  setConfig({});
                }}
                className={inputClass}
              >
                {types.map((t) => (
                  <option key={t.id} value={t.id}>{t.name}</option>
                ))}
              </select>
            )}
          </div>

          {/* Address */}
          <div>
            <label className={labelClass}>Address</label>
            <input
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              className={inputClass}
              placeholder="192.168.1.100 or hostname"
            />
          </div>

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

          {/* Status */}
          <div>
            <label className={labelClass}>Status</label>
            <div className="flex items-center gap-3">
              <button
                type="button"
                onClick={() => setStatus("online")}
                className={`flex items-center gap-2 rounded-lg px-3 py-2 text-sm transition-colors ${
                  status === "online"
                    ? "bg-emerald-50 text-emerald-700 ring-1 ring-emerald-200 dark:bg-emerald-950/30 dark:text-emerald-400 dark:ring-emerald-800"
                    : "text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800"
                }`}
              >
                <div className="h-2 w-2 rounded-full bg-emerald-500" />
                Online
              </button>
              <button
                type="button"
                onClick={() => setStatus("offline")}
                className={`flex items-center gap-2 rounded-lg px-3 py-2 text-sm transition-colors ${
                  status === "offline"
                    ? "bg-zinc-100 text-zinc-700 ring-1 ring-zinc-300 dark:bg-zinc-800 dark:text-zinc-300 dark:ring-zinc-600"
                    : "text-zinc-500 hover:bg-zinc-100 dark:hover:bg-zinc-800"
                }`}
              >
                <div className="h-2 w-2 rounded-full bg-zinc-400" />
                Offline
              </button>
            </div>
          </div>

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

          {/* Tile Color */}
          <div>
            <label className={labelClass}>Tile Color</label>
            <div className="flex items-center gap-2">
              {COLOR_PRESETS.map((c) => (
                <button
                  key={c}
                  type="button"
                  onClick={() => setColor(c)}
                  className={`h-7 w-7 rounded-full border-2 transition-transform ${
                    color === c
                      ? "scale-110 border-zinc-900 dark:border-zinc-100"
                      : "border-transparent hover:scale-105"
                  }`}
                  style={{ backgroundColor: c }}
                />
              ))}
              <input
                type="color"
                value={color}
                onChange={(e) => setColor(e.target.value)}
                className="h-7 w-7 cursor-pointer rounded border-0 bg-transparent p-0"
                title="Custom color"
              />
            </div>
          </div>

          {/* Dynamic Config Fields */}
          {currentFields.length > 0 && (
            <div>
              <div className="mb-2 border-t border-zinc-200 pt-4 dark:border-zinc-700">
                <label className="block text-xs font-semibold uppercase tracking-wider text-zinc-400">
                  Configuration
                </label>
              </div>
              <div className="space-y-3">
                {currentFields.map((field) => (
                  <div key={field.key}>
                    <label className={labelClass}>
                      {field.label}
                      {field.required && " *"}
                    </label>
                    <DynamicField
                      field={field}
                      value={config[field.key] ?? ""}
                      onChange={(val) => handleConfigChange(field.key, val)}
                    />
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="mt-6 flex items-center justify-between">
          <div>
            {editTool && onDelete && (
              <button
                type="button"
                onClick={onDelete}
                className="flex items-center gap-1.5 rounded-lg px-3 py-2 text-sm text-red-500 hover:bg-red-50 dark:hover:bg-red-950/30"
              >
                <Trash2 size={14} />
                Delete
              </button>
            )}
          </div>
          <div className="flex 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() || !typeId || missingRequired.length > 0}
              className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
            >
              {editTool ? "Save Changes" : "Add Tool"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
