'use client';

import { useEffect, useMemo, useState } from 'react';
import { Plus, Edit, Trash2, Search, Loader2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { createCategory, deleteCategory, fetchCategories, updateCategory } from '@/lib/services/categories';
import { slugify } from '@/lib/utils/slug';
import type { FrontendCategory } from '@/lib/types';

type ModalMode = 'create' | 'edit';

export default function AdminCategories() {
  const [categories, setCategories] = useState<FrontendCategory[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [modalMode, setModalMode] = useState<ModalMode | null>(null);
  const [selectedCategory, setSelectedCategory] = useState<FrontendCategory | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    slug: '',
    description: '',
    parentId: '',
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSlugDirty, setIsSlugDirty] = useState(false);

  useEffect(() => {
    let isMounted = true;

    async function loadCategories() {
      try {
        setIsLoading(true);
        setError(null);
        const data = await fetchCategories();
        if (!isMounted) return;
        setCategories(data);
      } catch (err) {
        console.error(err);
        if (isMounted) {
          setError('Unable to load categories');
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    void loadCategories();

    return () => {
      isMounted = false;
    };
  }, []);

  const handleOpenModal = (mode: ModalMode, category?: FrontendCategory) => {
    setModalMode(mode);
    if (mode === 'edit' && category) {
      setSelectedCategory(category);
      setFormData({
        name: category.name,
        slug: category.slug,
        description: category.description ?? '',
        parentId: category.parentId ?? '',
      });
      setIsSlugDirty(category.slug !== slugify(category.name));
    } else {
      setSelectedCategory(null);
      setFormData({
        name: '',
        slug: '',
        description: '',
        parentId: '',
      });
      setIsSlugDirty(false);
    }
  };

  const handleCloseModal = () => {
    setModalMode(null);
    setSelectedCategory(null);
    setFormData({
      name: '',
      slug: '',
      description: '',
      parentId: '',
    });
    setIsSlugDirty(false);
  };

  const handleSubmit = async () => {
    if (!formData.name.trim()) {
      setError('Name is required');
      toast.error('Name is required');
      return;
    }

    try {
      setIsSubmitting(true);
      setError(null);
      if (modalMode === 'create') {
        const category = await createCategory({
          name: formData.name.trim(),
          slug: formData.slug.trim() || undefined,
          description: formData.description.trim() || null,
          parentId: formData.parentId || null,
        });
        setCategories((prev) => [...prev, category]);
        toast.success('Category created successfully');
      } else if (modalMode === 'edit' && selectedCategory) {
        const updated = await updateCategory(selectedCategory.id, {
          name: formData.name.trim(),
          slug: formData.slug.trim() || undefined,
          description: formData.description.trim() || null,
          parentId: formData.parentId || null,
        });
        setCategories((prev) =>
          prev.map((category) => (category.id === selectedCategory.id ? updated : category))
        );
        toast.success('Category updated successfully');
      }
      handleCloseModal();
    } catch (err) {
      console.error(err);
      setError('Unable to save category. Please try again.');
      toast.error('Unable to save category. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleFieldChange = (
    field: 'name' | 'slug' | 'description' | 'parentId',
    value: string
  ) => {
    if (field === 'name') {
      setFormData((prev) => {
        const nextName = value;
        const autoSlug = slugify(nextName);
        return {
          ...prev,
          name: nextName,
          ...(isSlugDirty ? {} : { slug: autoSlug }),
        };
      });
    } else if (field === 'slug') {
      const trimmed = value.trim();
      setIsSlugDirty(trimmed.length > 0);
      setFormData((prev) => ({
        ...prev,
        slug: value,
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        [field]: value,
      }));
    }
  };

  const handleDelete = async (category: FrontendCategory) => {
    if (!confirm(`Delete category "${category.name}"?`)) {
      return;
    }

    try {
      await deleteCategory(category.id);
      setCategories((prev) => prev.filter((item) => item.id !== category.id));
      toast.success('Category deleted successfully');
    } catch (err) {
      console.error(err);
      setError('Unable to delete category.');
      toast.error('Unable to delete category.');
    }
  };

  const filteredCategories = useMemo(() => {
    const query = searchQuery.toLowerCase();
    return categories.filter((category) => category.name.toLowerCase().includes(query));
  }, [categories, searchQuery]);

  const subcategoriesMap = useMemo(() => {
    const map = new Map<string, FrontendCategory[]>();
    categories.forEach((category) => {
      if (category.parentId) {
        const items = map.get(category.parentId) ?? [];
        items.push(category);
        map.set(category.parentId, items);
      }
    });
    return map;
  }, [categories]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Categories</h1>
          <p className="text-gray-600 mt-1">Manage product categories</p>
          {error && <p className="text-sm text-red-600 mt-2">{error}</p>}
        </div>
        <button
          onClick={() => handleOpenModal('create')}
          className="flex items-center gap-2 bg-gray-900 text-white px-4 py-2 rounded-lg hover:bg-gray-800 transition-colors"
        >
          <Plus className="w-5 h-5" />
          Add Category
        </button>
      </div>

      <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search categories..."
            className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {isLoading ? (
          Array.from({ length: 6 }).map((_, index) => (
            <div key={index} className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 animate-pulse">
              <div className="h-6 bg-gray-200 rounded w-1/3 mb-3" />
              <div className="h-4 bg-gray-200 rounded w-2/3" />
            </div>
          ))
        ) : filteredCategories.length === 0 ? (
          <div className="col-span-full bg-white rounded-lg shadow-sm border border-gray-200 p-6 text-center text-sm text-gray-500">
            No categories found.
          </div>
        ) : (
          filteredCategories.map((category) => (
            <div
              key={category.id}
              className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow"
            >
              <div className="flex items-start justify-between mb-4">
                <div>
                  <h3 className="text-lg font-semibold text-gray-900">{category.name}</h3>
                  <p className="text-sm text-gray-500 mt-1">Slug: {category.slug}</p>
                  {category.parentId && (
                    <p className="text-xs text-gray-500 mt-1">
                      Parent:{' '}
                      {categories.find((item) => item.id === category.parentId)?.name || category.parentId}
                    </p>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleOpenModal('edit', category)}
                    className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded"
                    aria-label={`Edit ${category.name}`}
                  >
                    <Edit className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() => handleDelete(category)}
                    className="p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded"
                    aria-label={`Delete ${category.name}`}
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
              {category.description && <p className="text-sm text-gray-600 mb-4">{category.description}</p>}
              {subcategoriesMap.get(category.id)?.length ? (
                <div className="mt-4 pt-4 border-t border-gray-200">
                  <p className="text-xs font-medium text-gray-500 uppercase mb-2">Subcategories</p>
                  <div className="flex flex-wrap gap-2">
                    {subcategoriesMap.get(category.id)!.map((sub) => (
                      <span key={sub.id} className="px-2 py-1 text-xs bg-gray-100 text-gray-700 rounded">
                        {sub.name}
                      </span>
                    ))}
                  </div>
                </div>
              ) : null}
            </div>
          ))
        )}
      </div>

      {modalMode && (
        <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
          <div className="bg-white rounded-lg shadow-xl max-w-lg w-full p-6">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-2xl font-bold text-gray-900">
                {modalMode === 'create' ? 'Add New Category' : 'Edit Category'}
              </h2>
              {isSubmitting && <Loader2 className="w-4 h-4 animate-spin text-gray-400" />}
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Name *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => handleFieldChange('name', e.target.value)}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  placeholder="Luxury Pret"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Slug</label>
                <input
                  type="text"
                  value={formData.slug}
                  onChange={(e) => handleFieldChange('slug', e.target.value)}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  placeholder="luxury-pret"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Description</label>
                <textarea
                  value={formData.description}
                  onChange={(e) => handleFieldChange('description', e.target.value)}
                  rows={3}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  placeholder="Short description…"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Parent Category</label>
                <select
                  value={formData.parentId}
                  onChange={(e) => handleFieldChange('parentId', e.target.value)}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                >
                  <option value="">None</option>
                  {categories
                    .filter((category) => category.id !== selectedCategory?.id)
                    .map((category) => (
                      <option key={category.id} value={category.id}>
                        {category.name}
                      </option>
                    ))}
                </select>
              </div>
            </div>
            <div className="flex gap-3 mt-6">
              <button
                onClick={handleSubmit}
                disabled={isSubmitting}
                className="flex-1 bg-gray-900 text-white px-4 py-2 rounded-lg hover:bg-gray-800 transition-colors disabled:opacity-70 disabled:cursor-not-allowed"
              >
                {modalMode === 'create' ? 'Add Category' : 'Update Category'}
              </button>
              <button
                onClick={handleCloseModal}
                className="flex-1 bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-colors"
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

