"use client";

import { useState, useEffect } from "react";
import { X, Trash2 } from "lucide-react";
import type { AppEntry, AppHost, AppCategory, AppIcon } from "@/lib/types";
import { IconSelector } from "./IconSelector";

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

interface AppModalProps {
  open: boolean;
  onClose: () => void;
  onSave: (data: {
    name: string;
    url: string;
    hostId: string;
    categoryId: string;
    description?: string;
    icon: AppIcon;
    color: string;
  }) => void;
  onDelete?: () => void;
  editApp?: AppEntry | null;
  hosts: AppHost[];
  categories: AppCategory[];
  defaultHostId?: string;
  defaultCategoryId?: string;
  onUploadIcon: (file: File) => Promise<string>;
  onAddHost: (data: { name: string; address: string; description?: string }) => Promise<AppHost>;
  onAddCategory: (data: { name: string; description?: string }) => Promise<AppCategory>;
}

export function AppModal({
  open,
  onClose,
  onSave,
  onDelete,
  editApp,
  hosts,
  categories,
  defaultHostId,
  defaultCategoryId,
  onUploadIcon,
  onAddHost,
  onAddCategory,
}: AppModalProps) {
  const [name, setName] = useState("");
  const [url, setUrl] = useState("");
  const [hostId, setHostId] = useState("");
  const [categoryId, setCategoryId] = useState("");
  const [description, setDescription] = useState("");
  const [icon, setIcon] = useState<AppIcon>({ type: "lucide", value: "Box" });
  const [color, setColor] = useState(COLOR_PRESETS[0]);

  // Inline host creation
  const [showNewHost, setShowNewHost] = useState(false);
  const [newHostName, setNewHostName] = useState("");
  const [newHostAddress, setNewHostAddress] = useState("");
  const [newHostDesc, setNewHostDesc] = useState("");
  const [addingHost, setAddingHost] = useState(false);

  // Inline category creation
  const [showNewCategory, setShowNewCategory] = useState(false);
  const [newCatName, setNewCatName] = useState("");
  const [newCatDesc, setNewCatDesc] = useState("");
  const [addingCategory, setAddingCategory] = useState(false);

  useEffect(() => {
    if (open) {
      if (editApp) {
        setName(editApp.name);
        setUrl(editApp.url);
        setHostId(editApp.hostId);
        setCategoryId(editApp.categoryId);
        setDescription(editApp.description ?? "");
        setIcon(editApp.icon);
        setColor(editApp.color);
      } else {
        setName("");
        setUrl("");
        setHostId(defaultHostId ?? hosts[0]?.id ?? "");
        setCategoryId(defaultCategoryId ?? categories[0]?.id ?? "");
        setDescription("");
        setIcon({ type: "lucide", value: "Box" });
        setColor(COLOR_PRESETS[0]);
      }
      setShowNewHost(false);
      setShowNewCategory(false);
    }
  }, [open, editApp, hosts, categories, defaultHostId, defaultCategoryId]);

  if (!open) return null;

  const handleHostSelect = (val: string) => {
    if (val === "__new__") {
      setShowNewHost(true);
      setNewHostName("");
      setNewHostAddress("");
      setNewHostDesc("");
    } else {
      setHostId(val);
      setShowNewHost(false);
    }
  };

  const handleCategorySelect = (val: string) => {
    if (val === "__new__") {
      setShowNewCategory(true);
      setNewCatName("");
      setNewCatDesc("");
    } else {
      setCategoryId(val);
      setShowNewCategory(false);
    }
  };

  const handleCreateHost = async () => {
    if (!newHostName.trim() || !newHostAddress.trim()) return;
    setAddingHost(true);
    try {
      const host = await onAddHost({
        name: newHostName.trim(),
        address: newHostAddress.trim(),
        description: newHostDesc.trim() || undefined,
      });
      setHostId(host.id);
      setShowNewHost(false);
    } finally {
      setAddingHost(false);
    }
  };

  const handleCreateCategory = async () => {
    if (!newCatName.trim()) return;
    setAddingCategory(true);
    try {
      const cat = await onAddCategory({
        name: newCatName.trim(),
        description: newCatDesc.trim() || undefined,
      });
      setCategoryId(cat.id);
      setShowNewCategory(false);
    } finally {
      setAddingCategory(false);
    }
  };

  const handleSave = () => {
    if (!name.trim() || !url.trim()) return;
    onSave({
      name: name.trim(),
      url: url.trim(),
      hostId,
      categoryId,
      description: description.trim() || undefined,
      icon,
      color,
    });
  };

  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";

  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">
            {editApp ? "Edit App" : "Add App"}
          </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 App"
            />
          </div>

          {/* URL */}
          <div>
            <label className={labelClass}>URL *</label>
            <input
              type="url"
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              className={inputClass}
              placeholder="https://example.com"
            />
          </div>

          {/* Host */}
          <div>
            <label className={labelClass}>Host</label>
            <select
              value={showNewHost ? "__new__" : hostId}
              onChange={(e) => handleHostSelect(e.target.value)}
              className={inputClass}
            >
              {hosts.map((h) => (
                <option key={h.id} value={h.id}>
                  {h.name}
                </option>
              ))}
              <option value="__new__">Add new...</option>
            </select>
            {showNewHost && (
              <div className="mt-2 space-y-2 rounded-lg border border-zinc-200 p-3 dark:border-zinc-700">
                <input
                  value={newHostName}
                  onChange={(e) => setNewHostName(e.target.value)}
                  className={inputClass}
                  placeholder="Host name"
                />
                <input
                  value={newHostAddress}
                  onChange={(e) => setNewHostAddress(e.target.value)}
                  className={inputClass}
                  placeholder="Host address (e.g. 192.168.1.100)"
                />
                <input
                  value={newHostDesc}
                  onChange={(e) => setNewHostDesc(e.target.value)}
                  className={inputClass}
                  placeholder="Description (optional)"
                />
                <div className="flex justify-end gap-2">
                  <button
                    type="button"
                    onClick={() => setShowNewHost(false)}
                    className="rounded-lg px-3 py-1.5 text-sm text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    onClick={handleCreateHost}
                    disabled={addingHost}
                    className="rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
                  >
                    {addingHost ? "Adding..." : "Add Host"}
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* Category */}
          <div>
            <label className={labelClass}>Category</label>
            <select
              value={showNewCategory ? "__new__" : categoryId}
              onChange={(e) => handleCategorySelect(e.target.value)}
              className={inputClass}
            >
              {categories.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
              <option value="__new__">Add new...</option>
            </select>
            {showNewCategory && (
              <div className="mt-2 space-y-2 rounded-lg border border-zinc-200 p-3 dark:border-zinc-700">
                <input
                  value={newCatName}
                  onChange={(e) => setNewCatName(e.target.value)}
                  className={inputClass}
                  placeholder="Category name"
                />
                <input
                  value={newCatDesc}
                  onChange={(e) => setNewCatDesc(e.target.value)}
                  className={inputClass}
                  placeholder="Description (optional)"
                />
                <div className="flex justify-end gap-2">
                  <button
                    type="button"
                    onClick={() => setShowNewCategory(false)}
                    className="rounded-lg px-3 py-1.5 text-sm text-zinc-600 hover:bg-zinc-100 dark:text-zinc-400 dark:hover:bg-zinc-800"
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    onClick={handleCreateCategory}
                    disabled={addingCategory}
                    className="rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
                  >
                    {addingCategory ? "Adding..." : "Add Category"}
                  </button>
                </div>
              </div>
            )}
          </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={onUploadIcon} />
          </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>
        </div>

        {/* Footer */}
        <div className="mt-6 flex items-center justify-between">
          <div>
            {editApp && 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() || !url.trim()}
              className="rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
            >
              {editApp ? "Save Changes" : "Add App"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
