'use client';

import { useEffect, useMemo, useState } from 'react';
import { Plus, Edit, Trash2, Search, Loader2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { createColor, deleteColor, fetchColors, updateColor } from '@/lib/services/colors';
import type { FrontendColor } from '@/lib/types';

type ModalMode = 'create' | 'edit';

const defaultHex = '#000000';

export default function AdminColors() {
  const [colors, setColors] = useState<FrontendColor[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [modalMode, setModalMode] = useState<ModalMode | null>(null);
  const [selectedColor, setSelectedColor] = useState<FrontendColor | null>(null);
  const [formData, setFormData] = useState({ name: '', hex: defaultHex });
  const [isLoading, setIsLoading] = useState(true);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

    async function loadColors() {
      try {
        setIsLoading(true);
        setError(null);
        const data = await fetchColors();
        if (!isMounted) return;
        setColors(data);
      } catch (err) {
        console.error(err);
        if (isMounted) {
          setError('Unable to load colors');
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    void loadColors();

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

  const filteredColors = useMemo(() => {
    const query = searchQuery.toLowerCase();
    return colors.filter(
      (color) =>
        color.name.toLowerCase().includes(query) || color.hex.toLowerCase().includes(query)
    );
  }, [colors, searchQuery]);

  const handleOpenModal = (mode: ModalMode, color?: FrontendColor) => {
    setModalMode(mode);
    if (mode === 'edit' && color) {
      setSelectedColor(color);
      setFormData({ name: color.name, hex: color.hex });
    } else {
      setSelectedColor(null);
      setFormData({ name: '', hex: defaultHex });
    }
  };

  const handleCloseModal = () => {
    setModalMode(null);
    setSelectedColor(null);
    setFormData({ name: '', hex: defaultHex });
  };

  const handleSubmit = async () => {
    if (!formData.name.trim() || !formData.hex.trim()) {
      setError('Both name and hex code are required');
      toast.error('Both name and hex code are required');
      return;
    }

    try {
      setIsSubmitting(true);
      setError(null);

      if (modalMode === 'create') {
        const newColor = await createColor({
          name: formData.name.trim(),
          hex: formData.hex.trim(),
        });
        setColors((prev) => [...prev, newColor]);
        toast.success('Color created successfully');
      } else if (modalMode === 'edit' && selectedColor) {
        const updatedColor = await updateColor(selectedColor.id, {
          name: formData.name.trim(),
          hex: formData.hex.trim(),
        });
        setColors((prev) =>
          prev.map((color) => (color.id === selectedColor.id ? updatedColor : color))
        );
        toast.success('Color updated successfully');
      }

      handleCloseModal();
    } catch (err) {
      console.error(err);
      setError('Unable to save color. Please try again.');
      toast.error('Unable to save color. Please try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

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

    try {
      await deleteColor(color.id);
      setColors((prev) => prev.filter((item) => item.id !== color.id));
      toast.success('Color deleted successfully');
    } catch (err) {
      console.error(err);
      setError('Unable to delete color.');
      toast.error('Unable to delete color.');
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Colors</h1>
          <p className="text-gray-600 mt-1">Manage product colors</p>
          {error && <p className="mt-2 text-sm text-red-600">{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 Color
        </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 colors..."
            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-12 bg-gray-200 rounded w-12 mb-4" />
              <div className="h-4 bg-gray-200 rounded w-1/2" />
            </div>
          ))
        ) : filteredColors.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 colors found.
          </div>
        ) : (
          filteredColors.map((color) => (
            <div
              key={color.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">
                <div className="flex items-center gap-3">
                  <div
                    className="w-12 h-12 rounded-lg border-2 border-gray-200"
                    style={{ backgroundColor: color.hex }}
                  />
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900">{color.name}</h3>
                    <p className="text-sm text-gray-500 mt-1">{color.hex}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => handleOpenModal('edit', color)}
                    className="p-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded"
                    aria-label={`Edit ${color.name}`}
                  >
                    <Edit className="w-4 h-4" />
                  </button>
                  <button
                    onClick={() => handleDelete(color)}
                    className="p-2 text-red-600 hover:text-red-700 hover:bg-red-50 rounded"
                    aria-label={`Delete ${color.name}`}
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </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-md 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 Color' : 'Edit Color'}
              </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">Color Name *</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))}
                  placeholder="e.g., Black, Red, Blue"
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">Hex Code *</label>
                <div className="flex items-center gap-3">
                  <input
                    type="color"
                    value={formData.hex}
                    onChange={(e) => setFormData((prev) => ({ ...prev, hex: e.target.value }))}
                    className="w-16 h-16 rounded border border-gray-300 cursor-pointer"
                  />
                  <input
                    type="text"
                    value={formData.hex}
                    onChange={(e) => setFormData((prev) => ({ ...prev, hex: e.target.value }))}
                    placeholder="#000000"
                    className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                  />
                </div>
              </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 Color' : 'Update Color'}
              </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>
  );
}

