"use client";

import { useState } from 'react';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import ReactLenis from "lenis/react";
import NavbarStyleFullscreen from '@/components/navbar/NavbarStyleFullscreen/NavbarStyleFullscreen';
import ButtonElasticEffect from '@/components/button/ButtonElasticEffect/ButtonElasticEffect';

// Simple unique ID generator to replace uuidv4
const generateUniqueId = () => Math.random().toString(36).substring(2, 9) + Date.now().toString(36);

interface Product {
  id: string;
  name: string;
  price: string;
  imageSrc: string;
  imageAlt?: string;
}

export default function AdminPage() {
  const [products, setProducts] = useState<Product[]>([
    { id: generateUniqueId(), name: "Classic Oxford", price: "$189.99", imageSrc: "http://img.b2bpic.net/free-photo/couple-sharing-tender-public-intimacy-moments_23-2149430276.jpg", imageAlt: "Classic Black Oxford Shoe" },
    { id: generateUniqueId(), name: "Crimson Stiletto", price: "$159.99", imageSrc: "http://img.b2bpic.net/free-photo/lady-red-dress-coquettishly-raises-her-leg-while-sitting-restaurant-fulllength-photo-girl-with-short-hair-grey-tshirt-beige-jacket-posing-cafe_197531-26215.jpg", imageAlt: "Elegant Crimson Stiletto Heel" },
    { id: generateUniqueId(), name: "Urban White Sneaker", price: "$99.99", imageSrc: "http://img.b2bpic.net/free-photo/romantic-couple-moment-city_329181-12530.jpg", imageAlt: "Modern White Urban Sneaker" }
  ]);

  const [newProductName, setNewProductName] = useState('');
  const [newProductPrice, setNewProductPrice] = useState('');
  const [newProductImage, setNewProductImage] = useState('');
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);

  const navItems = [
    { name: "Home", id: "/" },
    { name: "Products", id: "/products" },
    { name: "Features", id: "#features" },
    { name: "About", id: "#about" },
    { name: "Testimonials", id: "#testimonials" },
    { name: "FAQ", id: "#faq" },
    { name: "Contact", id: "#contact" },
    { name: "Admin", id: "/admin" }
  ];

  const handleAddOrUpdateProduct = (e: React.FormEvent) => {
    e.preventDefault();
    if (!newProductName || !newProductPrice || !newProductImage) return;

    if (editingProduct) {
      setProducts(products.map(p =>
        p.id === editingProduct.id
          ? { ...p, name: newProductName, price: newProductPrice, imageSrc: newProductImage } as Product
          : p
      ));
      setEditingProduct(null);
    } else {
      const newProduct: Product = {
        id: generateUniqueId(),
        name: newProductName,
        price: newProductPrice,
        imageSrc: newProductImage,
        imageAlt: newProductName // Simple alt text for new products
      };
      setProducts([...products, newProduct]);
    }
    setNewProductName('');
    setNewProductPrice('');
    setNewProductImage('');
  };

  const startEdit = (product: Product) => {
    setEditingProduct(product);
    setNewProductName(product.name);
    setNewProductPrice(product.price);
    setNewProductImage(product.imageSrc);
  };

  const cancelEdit = () => {
    setEditingProduct(null);
    setNewProductName('');
    setNewProductPrice('');
    setNewProductImage('');
  };

  const deleteProduct = (id: string) => {
    setProducts(products.filter(p => p.id !== id));
    if (editingProduct && editingProduct.id === id) {
      cancelEdit();
    }
  };

  return (
    <ThemeProvider
      defaultButtonVariant="text-shift"
      defaultTextAnimation="background-highlight"
      borderRadius="pill"
      contentWidth="small"
      sizing="medium"
      background="noise"
      cardStyle="glass-elevated"
      primaryButtonStyle="shadow"
      secondaryButtonStyle="glass"
      headingFontWeight="normal"
    >
      <ReactLenis root>
        <div id="nav" data-section="nav">
          <NavbarStyleFullscreen
            navItems={navItems}
            logoSrc="http://img.b2bpic.net/free-vector/flat-design-cross-country-template_23-2149493304.jpg"
            logoAlt="Sole & Style Logo"
            brandName="Sole & Style"
            bottomLeftText="Luxury Footwear"
            bottomRightText="info@solenstyle.com"
          />
        </div>

        <main className="container mx-auto px-4 py-8 max-w-4xl">
          <h1 className="text-4xl font-bold mb-8 text-center">Product Management Admin View</h1>

          <section className="mb-12 p-6 border border-gray-200 rounded-xl shadow-lg bg-white/5 backdrop-blur-sm">
            <h2 className="text-2xl font-semibold mb-6 text-gray-800 dark:text-gray-100">{editingProduct ? 'Edit Product' : 'Add New Product'}</h2>
            <form onSubmit={handleAddOrUpdateProduct} className="space-y-4">
              <div>
                <label htmlFor="product-name" className="block text-sm font-medium text-gray-700 dark:text-gray-300">Product Name</label>
                <input
                  type="text"
                  id="product-name"
                  value={newProductName}
                  onChange={(e) => setNewProductName(e.target.value)}
                  required
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-3 bg-white/10 text-gray-900 dark:text-gray-100 dark:border-gray-700 focus:ring-primary-cta focus:border-primary-cta"
                />
              </div>
              <div>
                <label htmlFor="product-price" className="block text-sm font-medium text-gray-700 dark:text-gray-300">Price</label>
                <input
                  type="text"
                  id="product-price"
                  value={newProductPrice}
                  onChange={(e) => setNewProductPrice(e.target.value)}
                  required
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-3 bg-white/10 text-gray-900 dark:text-gray-100 dark:border-gray-700 focus:ring-primary-cta focus:border-primary-cta"
                />
              </div>
              <div>
                <label htmlFor="product-image" className="block text-sm font-medium text-gray-700 dark:text-gray-300">Image URL</label>
                <input
                  type="url"
                  id="product-image"
                  value={newProductImage}
                  onChange={(e) => setNewProductImage(e.target.value)}
                  required
                  className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm p-3 bg-white/10 text-gray-900 dark:text-gray-100 dark:border-gray-700 focus:ring-primary-cta focus:border-primary-cta"
                />
              </div>
              <div className="flex space-x-4">
                <ButtonElasticEffect text={editingProduct ? 'Update Product' : 'Add Product'} type="submit" className="min-w-[150px]" />
                {editingProduct && <ButtonElasticEffect text="Cancel Edit" onClick={cancelEdit} className="min-w-[150px]" />}
              </div>
            </form>
          </section>

          <section className="p-6 border border-gray-200 rounded-xl shadow-lg bg-white/5 backdrop-blur-sm">
            <h2 className="text-2xl font-semibold mb-6 text-gray-800 dark:text-gray-100">Existing Products</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {products.map((product) => (
                <div key={product.id} className="border border-gray-300 rounded-lg p-4 flex flex-col items-center text-center bg-white/10 dark:bg-gray-800/20">
                  <img src={product.imageSrc} alt={product.name} className="w-32 h-32 object-cover rounded-md mb-4 shadow-sm" />
                  <h3 className="text-lg font-semibold text-gray-900 dark:text-gray-50 mb-1">{product.name}</h3>
                  <p className="text-primary-cta mb-4 font-medium">{product.price}</p>
                  <div className="flex space-x-2">
                    <ButtonElasticEffect text="Edit" onClick={() => startEdit(product)} />
                    <ButtonElasticEffect text="Delete" onClick={() => deleteProduct(product.id)} />
                  </div>
                </div>
              ))}
            </div>
          </section>
        </main>
      </ReactLenis>
    </ThemeProvider>
  );
}
