import { LinearGradient } from "expo-linear-gradient";
import { useLocalSearchParams, useRouter } from "expo-router";
import React, { useEffect, useState } from "react";
import {
    Pressable,
    ScrollView,
    useWindowDimensions,
    View,
} from "react-native";

// services & hooks
import { useOrder } from "../hooks/useOrder";

// UI & theme
import AppScreen from "../src/components/ui/AppScreen";
import AppText from "../src/components/ui/AppText";
import { gradients } from "../src/theme/gradients";

// styles
import { takenoteStyles as styles } from "../src/styles/takenote";

type Product = {
  id: string;
  name: string;
  price: number;
  stock: number;
  category: string;
};

export default function TakeNote() {
  const params = useLocalSearchParams();
  const table = params.table as string;
  const router = useRouter();
  const { width: screenWidth } = useWindowDimensions();

  const isSmallScreen = screenWidth < 768;

  // Desktop widths
  const categoryWidth = isSmallScreen ? screenWidth * 0.25 : screenWidth * 0.22;
  const productWidth = isSmallScreen ? screenWidth * 0.4 : screenWidth * 0.38;
  const orderWidth = screenWidth - categoryWidth - productWidth - 60;

  const [categories, setCategories] = useState<string[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);

  const { order, addItem, removeOne, getQuantity, total } = useOrder();

  // Load categories
  useEffect(() => {
    getCategories().then(setCategories);
  }, []);

  // Load products for selected category
  useEffect(() => {
    if (selectedCategory) {
      getProductsByCategory(selectedCategory).then((items) =>
        setProducts(items as Product[])
      );
    } else {
      setProducts([]);
    }
  }, [selectedCategory]);

  const handleSendOrder = async () => {
    const newOrder = {
      products: order.map((item) => ({
        name: item.name,
        price: item.price,
        quantity: item.quantity,
      })),
      taula: table,
      total_price: total,
    };

    const savedOrder = await createOrder(newOrder);
    alert(`✅ Order sent! ID: ${savedOrder.id}`);
    router.back();
  };

  /* ---------------- LAYOUT MÓVIL (VERTICAL) ---------------- */

  if (isSmallScreen) {
    return (
      <AppScreen>
        <ScrollView contentContainerStyle={{ paddingBottom: 24 }}>
          {/* Header */}
          <View style={styles.header}>
            <Pressable style={styles.backButton} onPress={() => router.back()}>
              <AppText style={styles.backText}>← Back</AppText>
            </Pressable>
            <AppText style={styles.title}>{table.toUpperCase()}</AppText>
          </View>

          {/* Categories (horizontal chips) */}
          <AppText style={styles.sectionTitle}>Categories</AppText>
          <ScrollView
            horizontal
            showsHorizontalScrollIndicator={false}
            style={{ marginBottom: 16 }}
          >
            {categories.map((cat) => {
              const selected = selectedCategory === cat;
              return (
                <Pressable
                  key={cat}
                  style={[
                    styles.categoryButton,
                    { marginRight: 10, minWidth: 100 },
                    selected && styles.categorySelected,
                  ]}
                  onPress={() => setSelectedCategory(cat)}
                >
                  <AppText
                    style={[
                      styles.categoryText,
                      selected && styles.categoryTextSelected,
                    ]}
                  >
                    {cat}
                  </AppText>
                </Pressable>
              );
            })}
          </ScrollView>

          {/* Products */}
          <AppText style={styles.sectionTitle}>Products</AppText>
          <ScrollView
            showsVerticalScrollIndicator={false}
            style={{ marginBottom: 20 }}
          >
            <View style={styles.productGrid}>
              {products.map((prod) => {
                const qty = getQuantity(prod.name);
                const selected = qty > 0;

                return (
                  <Pressable
                    key={prod.id}
                    style={[
                      styles.productButton,
                      { width: "48%", height: 65 },
                      selected && styles.productSelected,
                    ]}
                    onPress={() => addItem(prod.name, prod.price)}
                  >
                    <AppText
                      style={[
                        styles.productText,
                        selected && styles.productTextSelected,
                      ]}
                    >
                      {prod.name}
                    </AppText>

                    {qty > 0 && (
                      <View style={styles.productBadge}>
                        <AppText style={styles.productBadgeText}>{qty}</AppText>
                      </View>
                    )}
                  </Pressable>
                );
              })}
            </View>
          </ScrollView>

          {/* Order summary (debajo en móvil) */}
          <View style={[styles.orderContainer, { marginBottom: 10 }]}>
            <AppText style={styles.orderTitle}>Order Summary</AppText>

            <ScrollView style={styles.orderList}>
              {order.map((item) => (
                <View key={item.name} style={styles.orderItem}>
                  <View style={styles.orderItemInfo}>
                    <AppText style={styles.orderText}>{item.name}</AppText>
                    <AppText style={styles.orderPrice}>
                      €{(item.quantity * item.price).toFixed(2)}
                    </AppText>
                  </View>

                  <View style={styles.quantityContainer}>
                    <Pressable
                      style={styles.quantityButton}
                      onPress={() => removeOne(item.name)}
                    >
                      <AppText style={styles.quantityText}>-</AppText>
                    </Pressable>

                    <AppText style={styles.quantityValue}>
                      {item.quantity}
                    </AppText>

                    <Pressable
                      style={styles.quantityButton}
                      onPress={() => addItem(item.name, item.price)}
                    >
                      <AppText style={styles.quantityText}>+</AppText>
                    </Pressable>
                  </View>
                </View>
              ))}
            </ScrollView>

            <View style={styles.footer}>
              <AppText style={styles.total}>
                Total: €{total.toFixed(2)}
              </AppText>

              <Pressable
                style={({ pressed }) => [
                  styles.sendButtonWrapper,
                  pressed && order.length > 0 && { transform: [{ scale: 0.98 }] },
                  order.length === 0 && { opacity: 0.5 },
                ]}
                disabled={order.length === 0}
                onPress={handleSendOrder}
              >
                <LinearGradient
                  colors={gradients.button}
                  style={styles.sendButton}
                >
                  <AppText style={styles.sendText}>Send Order</AppText>
                </LinearGradient>
              </Pressable>
            </View>
          </View>
        </ScrollView>
      </AppScreen>
    );
  }

  /* ------------- LAYOUT ESCRITORIO / TABLET ANCHA (3 COLS) ------------- */

  const productButtonWidth = productWidth / 2 - 12;

  return (
    <AppScreen>
      {/* Header */}
      <View style={styles.header}>
        <Pressable style={styles.backButton} onPress={() => router.back()}>
          <AppText style={styles.backText}>← Back</AppText>
        </Pressable>
        <AppText style={styles.title}>{table.toUpperCase()}</AppText>
      </View>

      <View style={styles.mainRow}>
        {/* Categories */}
        <View style={[styles.column, { width: categoryWidth }]}>
          <AppText style={styles.sectionTitle}>Categories</AppText>
          <ScrollView showsVerticalScrollIndicator={false}>
            {categories.map((cat) => {
              const selected = selectedCategory === cat;
              return (
                <Pressable
                  key={cat}
                  style={[
                    styles.categoryButton,
                    selected && styles.categorySelected,
                  ]}
                  onPress={() => setSelectedCategory(cat)}
                >
                  <AppText
                    style={[
                      styles.categoryText,
                      selected && styles.categoryTextSelected,
                    ]}
                  >
                    {cat}
                  </AppText>
                </Pressable>
              );
            })}
          </ScrollView>
        </View>

        {/* Products */}
        <View style={[styles.column, { width: productWidth }]}>
          <AppText style={styles.sectionTitle}>Products</AppText>
          <ScrollView showsVerticalScrollIndicator>
            <View style={styles.productGrid}>
              {products.map((prod) => {
                const qty = getQuantity(prod.name);
                const selected = qty > 0;

                return (
                  <Pressable
                    key={prod.id}
                    style={[
                      styles.productButton,
                      {
                        width: productButtonWidth,
                        height: 65,
                        marginBottom: 10,
                      },
                      selected && styles.productSelected,
                    ]}
                    onPress={() => addItem(prod.name, prod.price)}
                  >
                    <AppText
                      style={[
                        styles.productText,
                        selected && styles.productTextSelected,
                      ]}
                    >
                      {prod.name}
                    </AppText>

                    {qty > 0 && (
                      <View style={styles.productBadge}>
                        <AppText style={styles.productBadgeText}>{qty}</AppText>
                      </View>
                    )}
                  </Pressable>
                );
              })}
            </View>
          </ScrollView>
        </View>

        {/* Order summary */}
        <View style={[styles.orderContainer, { width: orderWidth }]}>
          <AppText style={styles.orderTitle}>Order Summary</AppText>

          <ScrollView style={styles.orderList}>
            {order.map((item) => (
              <View key={item.name} style={styles.orderItem}>
                <View style={styles.orderItemInfo}>
                  <AppText style={styles.orderText}>{item.name}</AppText>
                  <AppText style={styles.orderPrice}>
                    €{(item.quantity * item.price).toFixed(2)}
                  </AppText>
                </View>

                <View style={styles.quantityContainer}>
                  <Pressable
                    style={styles.quantityButton}
                    onPress={() => removeOne(item.name)}
                  >
                    <AppText style={styles.quantityText}>-</AppText>
                  </Pressable>

                  <AppText style={styles.quantityValue}>
                    {item.quantity}
                  </AppText>

                  <Pressable
                    style={styles.quantityButton}
                    onPress={() => addItem(item.name, item.price)}
                  >
                    <AppText style={styles.quantityText}>+</AppText>
                  </Pressable>
                </View>
              </View>
            ))}
          </ScrollView>

          <View style={styles.footer}>
            <AppText style={styles.total}>
              Total: €{total.toFixed(2)}
            </AppText>

            <Pressable
              style={({ pressed }) => [
                styles.sendButtonWrapper,
                pressed && order.length > 0 && { transform: [{ scale: 0.98 }] },
                order.length === 0 && { opacity: 0.5 },
              ]}
              disabled={order.length === 0}
              onPress={handleSendOrder}
            >
              <LinearGradient
                colors={gradients.button}
                style={styles.sendButton}
              >
                <AppText style={styles.sendText}>Send Order</AppText>
              </LinearGradient>
            </Pressable>
          </View>
        </View>
      </View>
    </AppScreen>
  );
}
