'use client';

import { useEffect, useRef, useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import toast from 'react-hot-toast';
import { ArrowLeft, Loader2, Save, Upload, X } from 'lucide-react';
import RichTextEditor from '@/app/components/RichTextEditor';
import { createProduct } from '@/lib/services/products';
import { fetchCategories } from '@/lib/services/categories';
import { fetchColors } from '@/lib/services/colors';
import { fetchSizes } from '@/lib/services/sizes';
import type { FrontendCategory, FrontendColor, FrontendSize } from '@/lib/types';

const slugify = (value: string) =>
  value
    .toLowerCase()
    .trim()
    .replace(/[\s\W-]+/g, '-')
    .replace(/^-+|-+$/g, '');

const SIZE_ORDER = ['XXS', 'XS', 'S', 'M', 'ML', 'L', 'XL', 'XXL', 'XXXL'];

export default function AddProduct() {
  const router = useRouter();
  const [formData, setFormData] = useState({
    name: '',
    slug: '',
    shortDescription: '',
    description: '',
    price: '',
    currency: 'USD',
    isImmediateDelivery: false,
    weight: '',
    weightUnit: 'kg',
  });
  const [thumbnail, setThumbnail] = useState<string>('');
  const [selectedImages, setSelectedImages] = useState<string[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [categories, setCategories] = useState<FrontendCategory[]>([]);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [colors, setColors] = useState<FrontendColor[]>([]);
  const [selectedColors, setSelectedColors] = useState<string[]>([]);
  const [sizes, setSizes] = useState<FrontendSize[]>([]);
  const [selectedSizes, setSelectedSizes] = useState<string[]>([]);
  const [isLoadingCategories, setIsLoadingCategories] = useState(true);
  const [isLoadingMeta, setIsLoadingMeta] = useState(true);
  const thumbnailInputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isSlugDirty, setIsSlugDirty] = useState(false);

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

    async function loadCategories() {
      try {
        const [categoriesData, colorsData, sizesData] = await Promise.all([
          fetchCategories(),
          fetchColors(),
          fetchSizes(),
        ]);
        if (!isMounted) return;
        setCategories(categoriesData);
        setColors(colorsData);
        setSizes(sizesData);
      } catch (err) {
        console.error(err);
        if (isMounted) {
          setError('Failed to load categories');
        }
      } finally {
        if (isMounted) {
          setIsLoadingCategories(false);
          setIsLoadingMeta(false);
        }
      }
    }

    void loadCategories();

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

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, type, value: rawValue } = e.target;
    const value = type === 'checkbox' ? (e.target as HTMLInputElement).checked : rawValue;

    if (name === 'slug') {
      setIsSlugDirty(Boolean(value));
    }

    setFormData((prev) => {
      if (name === 'name' && typeof value === 'string') {
        return {
          ...prev,
          name: value,
          ...(isSlugDirty ? {} : { slug: slugify(value) }),
        };
      }

      return {
        ...prev,
        [name]: value,
      };
    });
  };


  const toggleSelection = (value: string, items: string[], setItems: (items: string[]) => void) => {
    if (items.includes(value)) {
      setItems(items.filter((item) => item !== value));
    } else {
      setItems([...items, value]);
    }
  };

  const sortedSizes = useMemo(() => {
    return [...sizes].sort((a, b) => {
      const indexA = SIZE_ORDER.indexOf(a.name.toUpperCase());
      const indexB = SIZE_ORDER.indexOf(b.name.toUpperCase());
      if (indexA === -1 && indexB === -1) return a.name.localeCompare(b.name);
      if (indexA === -1) return 1;
      if (indexB === -1) return -1;
      return indexA - indexB;
    });
  }, [sizes]);

  const handleThumbnailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onloadend = () => setThumbnail(reader.result as string);
    reader.readAsDataURL(file);
  };

  const clearThumbnail = () => setThumbnail('');

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files || []);
    if (files.length === 0) return;

    const readers = files.map(
      (file) =>
        new Promise<string>((resolve) => {
          const reader = new FileReader();
          reader.onloadend = () => resolve(reader.result as string);
          reader.readAsDataURL(file);
        })
    );

    Promise.all(readers).then((results) => {
      setSelectedImages((prev) => [...prev, ...results]);
    });
  };

  const removeImage = (index: number) => {
    setSelectedImages((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!formData.name.trim()) {
      setError('Product name is required');
      toast.error('Product name is required');
      return;
    }

    if (selectedCategories.length === 0) {
      setError('Please select at least one category');
      toast.error('Please select at least one category');
      return;
    }

    const price = Number(formData.price);
    if (Number.isNaN(price) || price < 0) {
      setError('Price must be a valid positive number');
      toast.error('Price must be a valid positive number');
      return;
    }

    const galleryImages = selectedImages.map((url, index) => ({
      url,
      alt: `${formData.name} gallery image ${index + 1}`,
      isMain: false,
      isHover: false,
      order: index,
    }));

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

      await createProduct({
        name: formData.name.trim(),
        slug: formData.slug.trim() || slugify(formData.name),
        shortDescription: formData.shortDescription.trim(),
        description: formData.description,
        price,
        currency: formData.currency,
        isImmediateDelivery: formData.isImmediateDelivery,
        weight: formData.weight ? Number(formData.weight) : null,
        weightUnit: formData.weight ? formData.weightUnit : null,
        categories: selectedCategories,
        images: galleryImages,
        thumbnail: thumbnail ? { url: thumbnail, alt: `${formData.name} thumbnail` } : undefined,
        colors: selectedColors,
        sizes: selectedSizes,
      });

      toast.success('Product created successfully');
      router.push('/admin/products');
    } catch (err) {
      console.error(err);
      setError('Failed to create product. Please review the form and try again.');
      toast.error('Failed to create product. Please review the form and try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/admin/products" className="p-2 hover:bg-gray-100 rounded-lg transition-colors">
          <ArrowLeft className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-3xl font-bold text-gray-900">Add New Product</h1>
          <p className="text-gray-600 mt-1">Create a new product in your catalog</p>
        </div>
      </div>

      {error && (
        <div className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
      )}

      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-xl font-semibold text-gray-900 mb-6">Basic Information</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">Product Name *</label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                required
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                placeholder="e.g., Midnight Velvet"
              />
            </div>
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">Slug</label>
              <input
                type="text"
                name="slug"
                value={formData.slug}
                onChange={handleChange}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                placeholder="auto-generated-from-name"
              />
              <p className="mt-1 text-xs text-gray-500">Leave blank to generate automatically based on the product name.</p>
            </div>
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">Short Description *</label>
              <textarea
                name="shortDescription"
                value={formData.shortDescription}
                onChange={handleChange}
                required
                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="Brief product description (1-2 sentences)..."
              />
            </div>
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">Full Description *</label>
              <div className="border border-gray-300 rounded-lg overflow-hidden">
                <div className="[&_.ck-editor]:h-[500px] [&_.ck-content]:min-h-[450px]">
                  <RichTextEditor
                    data={formData.description}
                    onChange={(description) =>
                      setFormData((prev) => ({ ...prev, description }))
                    }
                  />
                </div>
              </div>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Price *</label>
              <input
                type="number"
                name="price"
                value={formData.price}
                onChange={handleChange}
                required
                step="0.01"
                min="0"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                placeholder="0.00"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Currency *</label>
              <select
                name="currency"
                value={formData.currency}
                onChange={handleChange}
                required
                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="USD">USD</option>
                <option value="PKR">PKR</option>
                <option value="GBP">GBP</option>
                <option value="EUR">EUR</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Weight (optional)</label>
              <input
                type="number"
                name="weight"
                value={formData.weight}
                onChange={handleChange}
                step="0.001"
                min="0"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                placeholder="0.000"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Weight Unit</label>
              <select
                name="weightUnit"
                value={formData.weightUnit}
                onChange={handleChange}
                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="kg">kg</option>
                <option value="lbs">lbs</option>
                <option value="g">g</option>
                <option value="oz">oz</option>
              </select>
            </div>
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-gray-700 mb-2">Categories *</label>
              <div className="flex flex-wrap gap-2">
                {categories.map((category) => (
                  <label
                    key={category.id}
                    className="flex items-center gap-2 px-3 py-2 border rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
                  >
                    <input
                      type="checkbox"
                      checked={selectedCategories.includes(category.slug)}
                      onChange={() => toggleSelection(category.slug, selectedCategories, setSelectedCategories)}
                      className="w-4 h-4 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
                    />
                    <span className="text-sm text-gray-700">{category.name}</span>
                  </label>
                ))}
              </div>
              {isLoadingCategories && categories.length === 0 && (
                <p className="text-xs text-gray-500 mt-2">Loading categories...</p>
              )}
              {!isLoadingCategories && categories.length === 0 && (
                <p className="text-xs text-gray-500 mt-2">No categories available. Add categories in the admin Categories section.</p>
              )}
              {selectedCategories.length === 0 && !isLoadingCategories && categories.length > 0 && (
                <p className="text-xs text-red-500 mt-2">Please select at least one category.</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Colors (optional)</label>
              <div className="flex flex-wrap gap-2">
                {colors.map((color) => (
                  <button
                    key={color.id}
                    type="button"
                    onClick={() => toggleSelection(color.id, selectedColors, setSelectedColors)}
                    className={`px-3 py-1 border rounded-full text-sm ${
                      selectedColors.includes(color.id)
                        ? 'bg-gray-900 text-white border-gray-900'
                        : 'bg-white text-gray-700 border-gray-300 hover:border-gray-400'
                    }`}
                  >
                    {color.name}
                  </button>
                ))}
              </div>
              {!isLoadingMeta && colors.length === 0 && (
                <p className="text-xs text-gray-500 mt-2">No colors available. Add colors in the admin Colors section.</p>
              )}
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Sizes (optional)</label>
              <div className="flex flex-wrap gap-2">
                {sortedSizes.map((size) => (
                  <button
                    key={size.id}
                    type="button"
                    onClick={() => toggleSelection(size.id, selectedSizes, setSelectedSizes)}
                    className={`px-3 py-1 border rounded-full text-sm ${
                      selectedSizes.includes(size.id)
                        ? 'bg-gray-900 text-white border-gray-900'
                        : 'bg-white text-gray-700 border-gray-300 hover:border-gray-400'
                    }`}
                  >
                    {size.name}
                  </button>
                ))}
              </div>
              {!isLoadingMeta && sizes.length === 0 && (
                <p className="text-xs text-gray-500 mt-2">No sizes available. Add sizes in the admin Sizes section.</p>
              )}
            </div>
            <div className="flex items-center">
              <input
                type="checkbox"
                name="isImmediateDelivery"
                checked={formData.isImmediateDelivery}
                onChange={handleChange}
                className="w-4 h-4 text-gray-900 border-gray-300 rounded focus:ring-gray-900"
              />
              <label className="ml-2 text-sm text-gray-700">Immediate Delivery Available</label>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-xl font-semibold text-gray-900 mb-6">Thumbnail Image</h2>
          <div className="space-y-4">
            {thumbnail ? (
              <div className="flex items-center gap-4">
                <div className="relative w-32 h-32 bg-gray-100 rounded-lg overflow-hidden border border-gray-200">
                  <img src={thumbnail} alt="Thumbnail preview" className="w-full h-full object-cover" />
                </div>
                <div className="flex flex-col gap-2">
                  <button
                    type="button"
                    onClick={() => thumbnailInputRef.current?.click()}
                    className="px-4 py-2 bg-gray-900 text-white rounded-lg hover:bg-gray-800 transition-colors"
                  >
                    Replace Thumbnail
                  </button>
                  <button
                    type="button"
                    onClick={clearThumbnail}
                    className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
                  >
                    Remove Thumbnail
                  </button>
                </div>
              </div>
            ) : (
              <button
                type="button"
                onClick={() => thumbnailInputRef.current?.click()}
                className="w-full border-2 border-dashed border-gray-300 rounded-lg p-12 text-center hover:border-gray-400 hover:bg-gray-50 transition-colors"
              >
                <div className="flex flex-col items-center justify-center">
                  <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                    <Upload className="w-8 h-8 text-gray-400" />
                  </div>
                  <p className="text-sm font-medium text-gray-700 mb-1">Click to upload thumbnail</p>
                  <p className="text-xs text-gray-500">Recommended size 1000x1000px or larger</p>
                </div>
              </button>
            )}
            <input
              ref={thumbnailInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleThumbnailChange}
            />
            <p className="text-xs text-gray-500">The thumbnail is used as the primary image for product listings.</p>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
          <h2 className="text-xl font-semibold text-gray-900 mb-6">Product Images</h2>
          <div className="relative">
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              multiple
              onChange={handleImageChange}
              className="hidden"
            />
            {selectedImages.length === 0 ? (
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                className="w-full border-2 border-dashed border-gray-300 rounded-lg p-12 text-center hover:border-gray-400 hover:bg-gray-50 transition-colors"
              >
                <div className="flex flex-col items-center justify-center">
                  <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                    <Upload className="w-8 h-8 text-gray-400" />
                  </div>
                  <p className="text-sm font-medium text-gray-700 mb-1">Click to upload images</p>
                  <p className="text-xs text-gray-500">Select multiple images for your product</p>
                </div>
              </button>
            ) : (
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                {selectedImages.map((image, index) => (
                  <div key={`${image}-${index}`} className="relative group">
                    <div className="relative aspect-square bg-gray-100 rounded-lg overflow-hidden border border-gray-200">
                      <img src={image} alt={`Product image ${index + 1}`} className="w-full h-full object-cover" />
                      <button
                        type="button"
                        onClick={() => removeImage(index)}
                        className="absolute top-2 right-2 bg-red-600 text-white p-1.5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-700"
                      >
                        <X className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                ))}
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="border-2 border-dashed border-gray-300 rounded-lg aspect-square flex items-center justify-center hover:border-gray-400 hover:bg-gray-50 transition-colors"
                >
                  <div className="text-center">
                    <Upload className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                    <p className="text-xs text-gray-500">Add more</p>
                  </div>
                </button>
              </div>
            )}
          </div>
        </div>

        <div className="flex items-center justify-end gap-4">
          <Link
            href="/admin/products"
            className="px-6 py-3 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
          >
            Cancel
          </Link>
          <button
            type="submit"
            disabled={isSubmitting}
            className="flex items-center gap-2 bg-gray-900 text-white px-6 py-3 rounded-lg hover:bg-gray-800 transition-colors disabled:cursor-not-allowed disabled:opacity-70"
          >
            {isSubmitting ? (
              <>
                <Loader2 className="w-5 h-5 animate-spin" />
                Saving…
              </>
            ) : (
              <>
                <Save className="w-5 h-5" />
                Save Product
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
}

