import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
} from 'react-native';
import { getStyles } from './providerDetailsScreen.styles';
import { Header, CatalogItemRow } from '@components';
import { useAppTheme } from '@theme';
import { useAppDispatch, useAppSelector } from '../../../hooks/useAppDispatch';
import { addItem } from '../../../store/cartSlice';
import { deliveryService } from '../../../services/deliveryService';
import { CatalogItem } from '../../../interfaces';

const CATEGORIES = ['Pizza', 'Sides', 'Beverages'];

export const ProviderDetailsScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const dispatch = useAppDispatch();
  const cartItems = useAppSelector((state) => state.cart.items);

  const [catalog, setCatalog] = useState<CatalogItem[]>([]);
  const [activeCategory, setActiveCategory] = useState(CATEGORIES[0]);

  useEffect(() => {
    deliveryService.getProviderCatalog('p1').then(setCatalog);
  }, []);

  const filteredItems = catalog.filter((item) => item.category === activeCategory);

  const getItemQuantity = (itemId: string) => {
    const item = cartItems.find((i) => i.item.id === itemId);
    return item ? item.quantity : 0;
  };

  const totalItems = cartItems.reduce((sum, i) => sum + i.quantity, 0);
  const totalPrice = cartItems.reduce(
    (sum, i) => sum + i.item.price * i.quantity,
    0,
  );

  return (
    <View style={styles.container}>
      <Header title="Provider Details" onBack={() => {}} />
      <ScrollView style={styles.content}>
        <View style={styles.hero}>
          <View style={styles.heroImage}>
            <Text style={styles.heroEmoji}>🍕</Text>
          </View>
          <Text style={styles.heroName}>Pizza Planet</Text>
          <View style={styles.heroStats}>
            <Text style={styles.heroStat}>⭐ 4.5</Text>
            <Text style={styles.heroStat}>🕐 25 min</Text>
            <Text style={styles.heroStat}>🍕 Italian</Text>
          </View>
        </View>

        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          style={styles.categoryRow}
        >
          {CATEGORIES.map((cat) => (
            <TouchableOpacity
              key={cat}
              style={[
                styles.categoryTab,
                activeCategory === cat && styles.categoryTabActive,
              ]}
              onPress={() => setActiveCategory(cat)}
              activeOpacity={0.7}
            >
              <Text
                style={[
                  styles.categoryTabText,
                  activeCategory === cat && styles.categoryTabTextActive,
                ]}
              >
                {cat}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>

        {filteredItems.map((item) => (
          <CatalogItemRow
            key={item.id}
            imageUrl={item.imageUrl}
            title={item.title}
            description={item.description}
            price={item.price}
            quantity={getItemQuantity(item.id)}
            onAdd={() =>
              dispatch(
                addItem({
                  providerId: 'p1',
                  providerName: 'Pizza Planet',
                  item,
                }),
              )
            }
            onRemove={() => {}}
          />
        ))}
      </ScrollView>

      {totalItems > 0 && (
        <View style={styles.cartStrip}>
          <Text style={styles.cartStripText}>
            {totalItems} Items | ₹{totalPrice}
          </Text>
          <TouchableOpacity style={styles.viewCartButton} activeOpacity={0.7}>
            <Text style={styles.viewCartText}>View Cart</Text>
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
};
