'use client';

import React from 'react';
import Link from 'next/link';
import { useCategories } from '@/hooks/useCategories';
import { Container } from '@/components/ui/container';
import { TypographyH3 } from '@/components/ui/typography';
import { Card } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/components/ui/breadcrumb';

const CategoriesPage = () => {
  const { categories, loading, error } = useCategories();

  // Debug logging
  console.log('CategoriesPage - categories:', categories);
  console.log('CategoriesPage - loading:', loading);
  console.log('CategoriesPage - error:', error);

  // Get parent categories
  const parentCategories = categories.filter(cat => cat.parent_id === null);
  console.log('CategoriesPage - parentCategories:', parentCategories);

  if (loading) {
    return (
      <div className="w-full px-4 md:px-6 py-12">
        <Container>
          <div className="animate-pulse space-y-8">
            <div className="h-8 bg-gray-200 rounded w-64"></div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {Array.from({ length: 6 }).map((_, i) => (
                <div key={i} className="h-64 bg-gray-200 rounded-lg"></div>
              ))}
            </div>
          </div>
        </Container>
      </div>
    );
  }

  if (error) {
    return (
      <div className="w-full px-4 md:px-6 py-12">
        <Container>
          <div className="text-center">
            <p className="text-red-500 mb-4">Error loading categories: {error}</p>
            <button 
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              Retry
            </button>
          </div>
        </Container>
      </div>
    );
  }

  return (
    <div className="w-full px-4 md:px-6 py-12 mb-14">
      <Container>
        {/* Breadcrumb */}
        <Breadcrumb className="mb-8">
          <BreadcrumbList>
            <BreadcrumbItem>
              <BreadcrumbLink href="/">Home</BreadcrumbLink>
            </BreadcrumbItem>
            <BreadcrumbSeparator />
            <BreadcrumbItem>
              <BreadcrumbPage>Categories</BreadcrumbPage>
            </BreadcrumbItem>
          </BreadcrumbList>
        </Breadcrumb>

        {/* Page Title */}
        <div className="mb-12 text-center">
          <TypographyH3 className="text-[36px] sm:text-[48px] leading-[44px] sm:leading-[58px] font-bold prompt tracking-[-0.94px] text-black">
            Shop by <span className="text-[#F5411C]">Categories</span>
          </TypographyH3>
          <p className="text-gray-600 mt-4 max-w-2xl mx-auto">
            Explore our wide range of product categories and find exactly what you&apos;re looking for.
          </p>
        </div>

        {/* Categories Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
          {parentCategories.map((category) => {
            const childrenCount = category.children?.length || 0;

            return (
              <Card 
                key={category.id} 
                className="group hover:shadow-xl transition-all duration-300 overflow-hidden border-2 hover:border-[#F5411C]"
              >
                <Link href={`/products?category=${category.id}`}>
                  <div className="p-6">
                    {/* Category Icon/Image */}
                    <div className="w-20 h-20 bg-[#F5411C]/10 rounded-full flex items-center justify-center mb-4 group-hover:bg-[#F5411C]/20 transition-colors">
                      <div className="w-12 h-12 relative">
                        {/* Using emoji as fallback since we don't have actual icons */}
                        <span className="text-4xl">
                          {category.name.includes('Fashion') && '👗'}
                          {category.name.includes('Electronics') && '💻'}
                          {category.name.includes('Home') && '🏠'}
                          {category.name.includes('Sports') && '⚽'}
                          {category.name.includes('Beauty') && '💄'}
                          {category.name.includes('Books') && '📚'}
                          {category.name.includes('Toys') && '🧸'}
                          {!['Fashion', 'Electronics', 'Home', 'Sports', 'Beauty', 'Books', 'Toys'].some(word => category.name.includes(word)) && '🛍️'}
                        </span>
                      </div>
                    </div>

                    {/* Category Name */}
                    <h3 className="text-2xl font-bold text-gray-900 mb-2 group-hover:text-[#F5411C] transition-colors">
                      {category.name}
                    </h3>

                    {/* Category Description */}
                    {category.description && (
                      <p className="text-gray-600 text-sm mb-4 line-clamp-2">
                        {category.description}
                      </p>
                    )}

                    {/* Subcategories Count */}
                    {childrenCount > 0 && (
                      <Badge variant="secondary" className="bg-gray-100 text-gray-700 hover:bg-gray-200 mb-4">
                        {childrenCount} {childrenCount === 1 ? 'Subcategory' : 'Subcategories'}
                      </Badge>
                    )}

                    {/* Subcategories List */}
                    {category.children && category.children.length > 0 && (
                      <div className="mt-4 pt-4 border-t">
                        <p className="text-xs font-semibold text-gray-500 uppercase mb-3">Subcategories</p>
                        <ul className="space-y-2">
                          {category.children.slice(0, 4).map((child) => (
                            <li key={child.id}>
                              <Link 
                                href={`/products?category=${child.id}`}
                                className="text-sm text-gray-700 hover:text-[#F5411C] transition-colors flex items-center group/item"
                                onClick={(e) => e.stopPropagation()}
                              >
                                <span className="w-1.5 h-1.5 bg-gray-400 rounded-full mr-2 group-hover/item:bg-[#F5411C]"></span>
                                {child.name}
                              </Link>
                            </li>
                          ))}
                          {category.children.length > 4 && (
                            <li className="text-sm text-[#F5411C] font-medium">
                              +{category.children.length - 4} more
                            </li>
                          )}
                        </ul>
                      </div>
                    )}

                    {/* Shop Now Button */}
                    <div className="mt-6">
                      <span className="inline-flex items-center text-[#F5411C] font-medium group-hover:gap-2 transition-all">
                        Shop Now 
                        <svg className="w-4 h-4 ml-1 group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                        </svg>
                      </span>
                    </div>
                  </div>
                </Link>
              </Card>
            );
          })}
        </div>

        {/* Empty State */}
        {parentCategories.length === 0 && (
          <div className="text-center py-12">
            <p className="text-gray-500 text-lg mb-4">No categories available at the moment.</p>
            <p className="text-sm text-gray-400">Total categories fetched: {categories.length}</p>
            <p className="text-sm text-gray-400">Parent categories: {parentCategories.length}</p>
          </div>
        )}
      </Container>
    </div>
  );
};

export default CategoriesPage;
