"use client";

import { useEffect, useState, useCallback } from "react";
import AdminLayout from "@/components/admin/AdminLayout";
import {
  PlusIcon,
  EditIcon,
  TrashIcon,
  LayersIcon,
  CheckIcon,
  XIcon,
  SpinnerIcon,
} from "@/components/Icons";

interface Service {
  id: number;
  title: string;
  shortDescription: string | null;
  description: string | null;
  icon: string | null;
  color: string | null;
  price: string | null;
  features: string | null;
  sortOrder: number | null;
  published: boolean | null;
}

const iconOptions = [
  { value: "server", label: "🖥️ Server" },
  { value: "code", label: "💻 Code" },
  { value: "brain", label: "🧠 Brain (AI)" },
  { value: "zap", label: "⚡ Zap (Automation)" },
  { value: "layers", label: "📦 Layers" },
  { value: "wallet", label: "💰 Wallet" },
  { value: "link", label: "🔗 Link (API)" },
  { value: "lightbulb", label: "💡 Lightbulb" },
];

const colorOptions = [
  { value: "#3b82f6", label: "Blue" },
  { value: "#8b5cf6", label: "Purple" },
  { value: "#06b6d4", label: "Cyan" },
  { value: "#10b981", label: "Green" },
  { value: "#f59e0b", label: "Amber" },
  { value: "#ef4444", label: "Red" },
  { value: "#ec4899", label: "Pink" },
  { value: "#a855f7", label: "Violet" },
];

export default function ServicesPage() {
  const [servicesList, setServicesList] = useState<Service[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editing, setEditing] = useState<Service | null>(null);
  const [saving, setSaving] = useState(false);

  const [formData, setFormData] = useState({
    title: "",
    shortDescription: "",
    description: "",
    icon: "code",
    color: "#3b82f6",
    price: "",
    features: "",
    published: true,
  });

  const fetchServices = useCallback(async () => {
    try {
      const res = await fetch("/api/admin/services");
      if (res.ok) {
        const data = await res.json();
        setServicesList(data.services);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchServices();
  }, [fetchServices]);

  const openForm = (service?: Service) => {
    if (service) {
      setEditing(service);
      setFormData({
        title: service.title,
        shortDescription: service.shortDescription || "",
        description: service.description || "",
        icon: service.icon || "code",
        color: service.color || "#3b82f6",
        price: service.price || "",
        features: service.features || "",
        published: service.published !== false,
      });
    } else {
      setEditing(null);
      setFormData({
        title: "",
        shortDescription: "",
        description: "",
        icon: "code",
        color: "#3b82f6",
        price: "",
        features: "",
        published: true,
      });
    }
    setShowForm(true);
  };

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);

    try {
      const url = editing
        ? `/api/admin/services/${editing.id}`
        : "/api/admin/services";
      const method = editing ? "PUT" : "POST";

      const res = await fetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (res.ok) {
        setShowForm(false);
        fetchServices();
      }
    } catch (e) {
      console.error(e);
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Delete this service?")) return;

    try {
      await fetch(`/api/admin/services/${id}`, { method: "DELETE" });
      setServicesList(servicesList.filter((s) => s.id !== id));
    } catch (e) {
      console.error(e);
    }
  };

  const getIconEmoji = (icon: string) => {
    const opt = iconOptions.find((o) => o.value === icon);
    return opt?.label.split(" ")[0] || "💻";
  };

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-text-primary">Services</h1>
            <p className="text-text-muted mt-1">
              Manage the services you offer
            </p>
          </div>
          <button
            onClick={() => openForm()}
            className="px-4 py-2.5 bg-gradient-to-r from-primary to-primary-light text-white font-semibold rounded-xl hover:shadow-lg hover:shadow-primary/25 transition-all flex items-center gap-2 text-sm"
          >
            <PlusIcon size={16} />
            Add Service
          </button>
        </div>

        {/* Services grid */}
        {loading ? (
          <div className="py-20 text-center">
            <SpinnerIcon size={40} className="text-primary mx-auto" />
          </div>
        ) : servicesList.length === 0 ? (
          <div className="glass rounded-xl p-12 text-center">
            <LayersIcon size={48} className="text-text-muted mx-auto mb-4" />
            <p className="text-text-muted text-lg mb-4">No services yet</p>
            <button
              onClick={() => openForm()}
              className="inline-flex items-center gap-1 text-primary-light hover:text-accent"
            >
              <PlusIcon size={14} /> Add your first service
            </button>
          </div>
        ) : (
          <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {servicesList.map((service) => (
              <div
                key={service.id}
                className="glass rounded-xl p-6 card-hover relative group"
              >
                {/* Status indicator */}
                <div
                  className={`absolute top-4 right-4 w-2 h-2 rounded-full ${
                    service.published ? "bg-success" : "bg-warning"
                  }`}
                  title={service.published ? "Published" : "Draft"}
                />

                {/* Icon */}
                <div
                  className="w-12 h-12 rounded-xl flex items-center justify-center text-2xl mb-4"
                  style={{ backgroundColor: `${service.color}20` }}
                >
                  {getIconEmoji(service.icon || "code")}
                </div>

                <h3 className="font-bold text-text-primary mb-2">
                  {service.title}
                </h3>
                <p className="text-sm text-text-secondary mb-4 line-clamp-2">
                  {service.shortDescription}
                </p>

                {service.price && (
                  <p
                    className="text-sm font-semibold mb-4"
                    style={{ color: service.color || "#6366f1" }}
                  >
                    {service.price}
                  </p>
                )}

                {/* Actions */}
                <div className="flex items-center gap-2 pt-4 border-t border-border opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    onClick={() => openForm(service)}
                    className="flex-1 py-2 text-sm font-medium text-text-secondary hover:text-primary-light rounded-lg hover:bg-white/5 transition-colors flex items-center justify-center gap-1"
                  >
                    <EditIcon size={14} /> Edit
                  </button>
                  <button
                    onClick={() => handleDelete(service.id)}
                    className="flex-1 py-2 text-sm font-medium text-text-secondary hover:text-danger rounded-lg hover:bg-danger/10 transition-colors flex items-center justify-center gap-1"
                  >
                    <TrashIcon size={14} /> Delete
                  </button>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* Form Modal */}
        {showForm && (
          <div
            className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4"
            onClick={(e) => {
              if (e.target === e.currentTarget) setShowForm(false);
            }}
          >
            <div className="bg-surface-card rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto border border-border">
              <div className="sticky top-0 bg-surface-card border-b border-border p-6 flex items-center justify-between">
                <h2 className="text-lg font-bold text-text-primary">
                  {editing ? "Edit Service" : "Add Service"}
                </h2>
                <button
                  onClick={() => setShowForm(false)}
                  className="p-2 text-text-muted hover:text-text-primary rounded-lg"
                >
                  <XIcon size={18} />
                </button>
              </div>

              <form onSubmit={handleSave} className="p-6 space-y-5">
                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Service Title *
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.title}
                    onChange={(e) =>
                      setFormData({ ...formData, title: e.target.value })
                    }
                    placeholder="e.g., Backend Development"
                    className="w-full"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Short Description
                  </label>
                  <input
                    type="text"
                    value={formData.shortDescription}
                    onChange={(e) =>
                      setFormData({ ...formData, shortDescription: e.target.value })
                    }
                    placeholder="Brief overview"
                    className="w-full"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Full Description
                  </label>
                  <textarea
                    rows={4}
                    value={formData.description}
                    onChange={(e) =>
                      setFormData({ ...formData, description: e.target.value })
                    }
                    placeholder="Detailed description"
                    className="w-full"
                  />
                </div>

                <div className="grid sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-sm font-medium text-text-secondary mb-1.5">
                      Icon
                    </label>
                    <select
                      value={formData.icon}
                      onChange={(e) =>
                        setFormData({ ...formData, icon: e.target.value })
                      }
                      className="w-full"
                    >
                      {iconOptions.map((opt) => (
                        <option key={opt.value} value={opt.value}>
                          {opt.label}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-text-secondary mb-1.5">
                      Color
                    </label>
                    <div className="flex items-center gap-2">
                      <input
                        type="color"
                        value={formData.color}
                        onChange={(e) =>
                          setFormData({ ...formData, color: e.target.value })
                        }
                        className="w-10 h-10 rounded-lg cursor-pointer"
                      />
                      <select
                        value={formData.color}
                        onChange={(e) =>
                          setFormData({ ...formData, color: e.target.value })
                        }
                        className="flex-1"
                      >
                        {colorOptions.map((opt) => (
                          <option key={opt.value} value={opt.value}>
                            {opt.label}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Price
                  </label>
                  <input
                    type="text"
                    value={formData.price}
                    onChange={(e) =>
                      setFormData({ ...formData, price: e.target.value })
                    }
                    placeholder="e.g., From $500 or $100/hour"
                    className="w-full"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-text-secondary mb-1.5">
                    Features (comma-separated)
                  </label>
                  <input
                    type="text"
                    value={formData.features}
                    onChange={(e) =>
                      setFormData({ ...formData, features: e.target.value })
                    }
                    placeholder="Feature 1, Feature 2, Feature 3"
                    className="w-full"
                  />
                </div>

                <label className="flex items-center gap-2 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={formData.published}
                    onChange={(e) =>
                      setFormData({ ...formData, published: e.target.checked })
                    }
                    className="w-4 h-4 rounded"
                  />
                  <span className="text-sm text-text-secondary">Published</span>
                </label>

                <div className="flex justify-end gap-3 pt-4 border-t border-border">
                  <button
                    type="button"
                    onClick={() => setShowForm(false)}
                    className="px-5 py-2.5 border border-border text-text-secondary rounded-xl hover:bg-white/5 transition-colors text-sm"
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    disabled={saving}
                    className="px-5 py-2.5 bg-primary text-white font-semibold rounded-xl hover:bg-primary-dark transition-colors flex items-center gap-2 text-sm disabled:opacity-50"
                  >
                    {saving ? (
                      <>
                        <SpinnerIcon size={16} />
                        Saving...
                      </>
                    ) : (
                      <>
                        <CheckIcon size={16} />
                        {editing ? "Update" : "Create"}
                      </>
                    )}
                  </button>
                </div>
              </form>
            </div>
          </div>
        )}
      </div>
    </AdminLayout>
  );
}
