import React, { useState, useEffect } from 'react'
import api from '../api'
import '../styles/global.css'

export default function ProductFilters({ onFilter }) {
  const [filters, setFilters] = useState({
    gender: '',
    brand: '',
    model_id: '',
    size: '',
    min_price: '',
    max_price: '',
    onSale: false,
  })
  
  const [brands, setBrands] = useState([])
  const [models, setModels] = useState([])
  const [sizes, setSizes] = useState([])

  useEffect(() => {
    fetchBrands()
    fetchSizes()
  }, [])

  useEffect(() => {
    if (filters.brand) {
      fetchModels(filters.brand)
    } else {
      setModels([])
      setFilters(prev => ({ ...prev, model_id: '' }))
    }
  }, [filters.brand])

  const fetchBrands = async () => {
    try {
      const response = await api.get('/products/filters/brands')
      setBrands(response.data)
    } catch (error) {
      console.error('Error fetching brands:', error)
    }
  }

  const fetchModels = async (brand) => {
    try {
      const response = await api.get(`/models?brand=${brand}`)
      setModels(response.data)
    } catch (error) {
      console.error('Error fetching models:', error)
    }
  }

  const fetchSizes = async () => {
    try {
      const response = await api.get('/products/filters/sizes')
      setSizes(response.data)
    } catch (error) {
      console.error('Error fetching sizes:', error)
    }
  }

  const handleFilterChange = (key, value) => {
    const newFilters = { ...filters, [key]: value }
    setFilters(newFilters)
    onFilter(newFilters)
  }

  const resetFilters = () => {
    const resetFilters = {
      gender: '',
      brand: '',
      model_id: '',
      size: '',
      min_price: '',
      max_price: '',
      onSale: false,
    }
    setFilters(resetFilters)
    onFilter(resetFilters)
  }

  return (
    <div className="filters-sidebar">
      <h3>Filters</h3>

      <div className="filter-group">
        <label>Gender</label>
        <select
          value={filters.gender}
          onChange={(e) => handleFilterChange('gender', e.target.value)}
        >
          <option value="">All</option>
          <option value="men">Men</option>
          <option value="women">Women</option>
        </select>
      </div>

      <div className="filter-group">
        <label>Brand</label>
        <select
          value={filters.brand}
          onChange={(e) => handleFilterChange('brand', e.target.value)}
        >
          <option value="">All Brands</option>
          {brands.map((brand, index) => (
            <option key={index} value={brand}>
              {brand}
            </option>
          ))}
        </select>
      </div>

      {filters.brand && models.length > 0 && (
        <div className="filter-group">
          <label>Model</label>
          <select
            value={filters.model_id}
            onChange={(e) => handleFilterChange('model_id', e.target.value)}
          >
            <option value="">All Models</option>
            {models.map((model) => (
              <option key={model.id} value={model.id}>
                {model.name}
              </option>
            ))}
          </select>
        </div>
      )}

      <div className="filter-group">
        <label>Size</label>
        <select
          value={filters.size}
          onChange={(e) => handleFilterChange('size', e.target.value)}
        >
          <option value="">All Sizes</option>
          {sizes.map((size, index) => (
            <option key={index} value={size}>
              {size}
            </option>
          ))}
        </select>
      </div>

      <div className="filter-group">
        <label>Price Range</label>
        <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
          <input
            type="number"
            placeholder="Min"
            value={filters.min_price}
            onChange={(e) => handleFilterChange('min_price', e.target.value)}
            style={{ width: '80px', padding: '0.5rem' }}
          />
          <span>-</span>
          <input
            type="number"
            placeholder="Max"
            value={filters.max_price}
            onChange={(e) => handleFilterChange('max_price', e.target.value)}
            style={{ width: '80px', padding: '0.5rem' }}
          />
        </div>
      </div>

      <div className="filter-group">
        <label>
          <input
            type="checkbox"
            checked={filters.onSale}
            onChange={(e) => handleFilterChange('onSale', e.target.checked)}
          />
          On Sale Only
        </label>
      </div>

      <button className="btn btn-full" onClick={resetFilters}>
        Reset Filters
      </button>
    </div>
  )
}
