'use client';

import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { ChevronDown, X } from 'lucide-react';
import Header from '../components/Header';
import Footer from '../components/Footer';
import ProductCard from '../components/ProductCard';
import RangeSlider from '@/components/ui/range-slider';
import { useCurrency } from '../context/CurrencyContext';
import { fetchProducts } from '@/lib/services/products';
import { fetchSizes } from '@/lib/services/sizes';
import { fetchColors } from '@/lib/services/colors';
import type {
  FrontendProductSummary,
  FrontendSize,
  FrontendColor,
} from '@/lib/types';

const PRICE_MIN = 0;
const PRICE_MAX = 500000;
const PRICE_STEP = 5000;

type SortOption = 'position' | 'price-low' | 'price-high' | 'name-asc' | 'name-desc';

export default function ShopPage() {
  const [sortBy, setSortBy] = useState<SortOption>('position');
  const [showFilters, setShowFilters] = useState(false);
  const [selectedSizes, setSelectedSizes] = useState<string[]>([]);
  const [selectedColors, setSelectedColors] = useState<string[]>([]);
  const [priceRange, setPriceRange] = useState<[number, number]>([PRICE_MIN, 0]);
  const [products, setProducts] = useState<FrontendProductSummary[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [availableSizes, setAvailableSizes] = useState<FrontendSize[]>([]);
  const [availableColors, setAvailableColors] = useState<FrontendColor[]>([]);
  const { selectedCurrency, formatCurrency } = useCurrency();

  const displayCurrencyLabel = selectedCurrency;
  const formattedMinPrice = formatCurrency(priceRange[0], {
    fromCurrency: 'PKR',
    maximumFractionDigits: 0,
    minimumFractionDigits: 0,
  });
  const formattedMaxPrice =
    priceRange[1] === 0
      ? 'No Limit'
      : formatCurrency(priceRange[1], {
          fromCurrency: 'PKR',
          maximumFractionDigits: 0,
          minimumFractionDigits: 0,
        });

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

    async function loadFilters() {
      try {
        const [sizesData, colorsData] = await Promise.all([
          fetchSizes(),
          fetchColors(),
        ]);

        if (!isMounted) {
          return;
        }

        setAvailableSizes(
          sizesData.sort((a, b) => a.order - b.order)
        );
        setAvailableColors(
          colorsData.sort((a, b) => a.name.localeCompare(b.name))
        );
      } catch (err) {
        console.error('Failed to load filter options', err);
      }
    }

    void loadFilters();

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

  useEffect(() => {
    setSelectedSizes((previous) =>
      previous.filter((value) =>
        availableSizes.some((size) => size.name === value)
      )
    );
  }, [availableSizes]);

  useEffect(() => {
    setSelectedColors((previous) =>
      previous.filter((value) =>
        availableColors.some((color) => color.name === value)
      )
    );
  }, [availableColors]);

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

    async function loadAllProducts() {
      setIsLoading(true);
      setError(null);

      try {
        const productsData = await fetchProducts({
          sizes: selectedSizes,
          colors: selectedColors,
          minPrice: priceRange[0],
          maxPrice: priceRange[1] === 0 ? null : priceRange[1],
          sort: sortBy,
        });

        if (!isMounted) {
          return;
        }

        setProducts(productsData);
      } catch (err) {
        console.error(err);
        if (isMounted) {
          setError('Unable to load products');
          setProducts([]);
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    void loadAllProducts();

    return () => {
      isMounted = false;
    };
  }, [selectedSizes, selectedColors, priceRange, sortBy]);

  const sliderValues: [number, number] = [
    priceRange[0],
    priceRange[1] === 0 ? PRICE_MAX : priceRange[1],
  ];

  if (isLoading) {
    return (
      <div className="min-h-screen flex flex-col">
        <Header />
        <main className="grow flex items-center justify-center">
          <p className="text-gray-500">Loading products...</p>
        </main>
        <Footer />
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex flex-col">
        <Header />
        <main className="grow flex items-center justify-center">
          <div className="text-center">
            <h1 className="text-4xl font-bold text-gray-900 mb-4">Error</h1>
            <p className="text-xl text-gray-600 mb-8">{error}</p>
            <Link href="/" className="bg-black text-white px-6 py-3 inline-block hover:bg-gray-800 transition-colors">
              Return Home
            </Link>
          </div>
        </main>
        <Footer />
      </div>
    );
  }

  return (
    <div className="min-h-screen flex flex-col">
      <Header />
      <main className="grow py-8">
        <div className="container mx-auto px-4">
          <nav className="text-sm text-gray-600 mb-6">
            <Link href="/" className="text-gray-900 hover:text-gray-700">HOME</Link>
            {' > '}
            <span className="text-gray-500">SHOP</span>
          </nav>

          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8 pb-4 border-b border-gray-200">
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="flex items-center gap-2 hover:opacity-70 transition-opacity cursor-pointer text-left"
            >
              {showFilters ? (
                <X className="w-5 h-5 text-gray-700" />
              ) : (
                <svg className="w-5 h-5 text-gray-700" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <circle cx="4" cy="6" r="1.5" fill="currentColor" />
                  <line x1="4" y1="6" x2="12" y2="6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                  <circle cx="4" cy="12" r="1.5" fill="currentColor" />
                  <line x1="4" y1="12" x2="16" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                  <circle cx="4" cy="18" r="1.5" fill="currentColor" />
                  <line x1="4" y1="18" x2="20" y2="18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
                </svg>
              )}
              <span className="text-md font-semibold text-gray-900 uppercase">REFINE SEARCH</span>
            </button>

            <div className="flex items-center md:justify-end gap-3">
              <span className="text-sm font-semibold text-gray-900 uppercase whitespace-nowrap">SORT BY</span>
              <div className="relative w-full md:w-auto">
                <select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value as SortOption)}
                  className="w-full appearance-none bg-white border border-gray-300 px-4 py-2 pr-8 text-sm text-gray-900 rounded focus:outline-none focus:border-gray-400 cursor-pointer"
                >
                  <option value="position">Position</option>
                  <option value="price-low">Price: Low to High</option>
                  <option value="price-high">Price: High to Low</option>
                  <option value="name-asc">Name: A to Z</option>
                  <option value="name-desc">Name: Z to A</option>
                </select>
                <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-600 pointer-events-none" />
              </div>
            </div>
          </div>

          <div className="flex flex-col lg:flex-row gap-8">
            {showFilters && (
              <div className="w-full lg:w-64 shrink-0">
                <div className="bg-white p-6 border border-gray-200 rounded-md lg:sticky lg:top-24">
                  <div className="mb-8">
                    <h3 className="text-sm font-semibold text-gray-900 uppercase mb-4 border-b border-black w-fit pb-2">
                      SIZE
                    </h3>
                    <div className="space-y-2">
                      {availableSizes.length > 0 ? (
                        availableSizes.map((size) => (
                          <label key={size.id} className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={selectedSizes.includes(size.name)}
                              onChange={(e) => {
                                if (e.target.checked) {
                                  setSelectedSizes([...selectedSizes, size.name]);
                                } else {
                                  setSelectedSizes(selectedSizes.filter((s) => s !== size.name));
                                }
                              }}
                              className="w-4 h-4 text-black border-gray-300 rounded focus:ring-black"
                            />
                            <span className="text-sm text-gray-700">{size.name}</span>
                          </label>
                        ))
                      ) : (
                        <p className="text-sm text-gray-500">No sizes available.</p>
                      )}
                    </div>
                  </div>

                  <div className="mb-8">
                    <h3 className="text-sm font-semibold text-gray-900 uppercase mb-4 border-b border-black w-fit pb-2">
                      COLOR
                    </h3>
                    <div className="space-y-2">
                      {availableColors.length > 0 ? (
                        availableColors.map((color) => (
                          <label key={color.id} className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={selectedColors.includes(color.name)}
                              onChange={(e) => {
                                if (e.target.checked) {
                                  setSelectedColors([...selectedColors, color.name]);
                                } else {
                                  setSelectedColors(selectedColors.filter((c) => c !== color.name));
                                }
                              }}
                              className="w-4 h-4 text-black border-gray-300 rounded focus:ring-black"
                            />
                            <span className="text-sm text-gray-700">{color.name}</span>
                          </label>
                        ))
                      ) : (
                        <p className="text-sm text-gray-500">No colors available.</p>
                      )}
                    </div>
                  </div>

                  <div>
                    <h3 className="text-sm font-semibold text-gray-900 uppercase mb-4 border-b border-black w-fit pb-2">
                      PRICE RANGE
                    </h3>
                    <div className="space-y-4">
                      <div className="flex items-center justify-between text-xs text-gray-600 uppercase tracking-wide">
                        <span>Min Price ({displayCurrencyLabel})</span>
                        <span className="text-gray-900 font-semibold">
                          {formattedMinPrice}
                        </span>
                      </div>
                      <div className="flex items-center justify-between text-xs text-gray-600 uppercase tracking-wide">
                        <span>Max Price ({displayCurrencyLabel})</span>
                        <span className="text-gray-900 font-semibold">
                          {formattedMaxPrice}
                        </span>
                      </div>
                      <RangeSlider
                        value={sliderValues}
                        min={PRICE_MIN}
                        max={PRICE_MAX}
                        step={PRICE_STEP}
                        onChange={(value) => {
                          const [minValue, maxValue] = Array.isArray(value)
                            ? (value as [number, number])
                            : [value, value];

                          const boundedMin = Math.max(Math.min(minValue, PRICE_MAX), PRICE_MIN);
                          const boundedMaxRaw = Math.max(Math.min(maxValue, PRICE_MAX), PRICE_MIN);

                          if (boundedMaxRaw >= PRICE_MAX) {
                            setPriceRange([boundedMin, 0]);
                            return;
                          }

                          const boundedMax = Math.max(boundedMaxRaw, boundedMin);
                          setPriceRange([boundedMin, boundedMax]);
                        }}
                      />
                      <p className="text-xs text-gray-500 leading-relaxed">
                        Drag the handles to set your preferred price range. Move the max handle fully right to show all prices above the minimum.
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            )}

            <div className="flex-1">
              {products.length > 0 ? (
                <div className="grid gap-8 grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3">
                  {products.map((product) => (
                    <ProductCard key={product.slug} product={product} />
                  ))}
                </div>
              ) : (
                <div className="text-center py-20">
                  <p className="text-gray-500 text-lg">No products found.</p>
                </div>
              )}
            </div>
          </div>
        </div>
      </main>
      <Footer />
    </div>
  );
}

