import React, { useState, useEffect, useMemo } from 'react';
import { View, Text, TextInput, TouchableOpacity, ScrollView, ActivityIndicator, Alert, Modal, SafeAreaView, Dimensions, KeyboardAvoidingView, Platform } from 'react-native';
import { FlashList } from '@shopify/flash-list';
import { useAuth } from '../context/AuthContext';
import { transaksiApi, orderApi } from '../lib/api';
import type { Product, Category, AvailableDiscount, CartItemData, CreateOrderPayload, StoreSettings } from '../types';

export const POSScreen: React.FC = () => {
  const { user, logout } = useAuth();
  
  // Loading & State
  const [isLoading, setIsLoading] = useState(true);
  const [products, setProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [discounts, setDiscounts] = useState<AvailableDiscount[]>([]);
  const [settings, setSettings] = useState<StoreSettings | null>(null);
  
  // Filters
  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<number | null>(null); // null = "Semua"
  
  // Cart State
  const [cart, setCart] = useState<CartItemData[]>([]);
  const [selectedDiscount, setSelectedDiscount] = useState<AvailableDiscount | null>(null);
  const [paymentMethod, setPaymentMethod] = useState<'cash' | 'transfer' | 'qris'>('cash');
  const [cashReceived, setCashReceived] = useState('');
  
  // Modals
  const [isCartVisible, setIsCartVisible] = useState(false);
  const [isDiscountModalVisible, setIsDiscountModalVisible] = useState(false);
  const [isSuccessModalVisible, setIsSuccessModalVisible] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // Success Order Info
  const [completedOrder, setCompletedOrder] = useState<{
    orderNumber: string;
    total: number;
    change: number;
  } | null>(null);

  // Responsive Dimensions
  const { width } = Dimensions.get('window');
  const isTablet = width > 768;

  // 1. Fetch initial data from Laravel Backend
  const loadPOSData = async () => {
    setIsLoading(true);
    try {
      const data = await transaksiApi.getInitData();
      setProducts(data.products || []);
      setCategories(data.categories || []);
      setDiscounts(data.discounts || []);
      setSettings(data.settings || null);
    } catch (e) {
      console.error('Failed to load POS init data', e);
      Alert.alert('Gagal Memuat Data', 'Tidak dapat terhubung ke server untuk mengambil data produk.');
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadPOSData();
  }, []);

  // 2. Filter products based on search & category
  const filteredProducts = useMemo(() => {
    return products.filter((p) => {
      const matchesCategory = selectedCategory === null || p.category_id === selectedCategory;
      const matchesSearch = p.name.toLowerCase().includes(search.toLowerCase()) || 
                            (p.barcode && p.barcode.includes(search)) || 
                            (p.sku && p.sku.toLowerCase().includes(search.toLowerCase()));
      return matchesCategory && matchesSearch && p.is_available;
    });
  }, [products, selectedCategory, search]);

  // 3. Cart Logic Functions
  const addToCart = (product: Product) => {
    if (product.stock <= 0) {
      Alert.alert('Stok Habis', `Stok untuk produk ${product.name} sudah kosong.`);
      return;
    }

    setCart((prevCart) => {
      const existingIndex = prevCart.findIndex((item) => item.product_id === product.id);
      
      if (existingIndex > -1) {
        const item = prevCart[existingIndex];
        if (item.quantity + 1 > product.stock) {
          Alert.alert('Stok Terbatas', `Batas stok produk ini adalah ${product.stock} ${product.unit}.`);
          return prevCart;
        }
        const updated = [...prevCart];
        updated[existingIndex] = {
          ...item,
          quantity: item.quantity + 1,
          subtotal: (item.quantity + 1) * item.unit_price,
        };
        return updated;
      } else {
        return [
          ...prevCart,
          {
            product_id: product.id,
            product_name: product.name,
            product_price: product.price,
            unit: product.unit,
            quantity: 1,
            unit_price: product.price,
            subtotal: product.price,
          },
        ];
      }
    });
  };

  const updateQuantity = (productId: number, change: number) => {
    const product = products.find((p) => p.id === productId);
    if (!product) return;

    setCart((prevCart) => {
      const existingIndex = prevCart.findIndex((item) => item.product_id === productId);
      if (existingIndex === -1) return prevCart;

      const item = prevCart[existingIndex];
      const newQty = item.quantity + change;

      if (newQty <= 0) {
        return prevCart.filter((i) => i.product_id !== productId);
      }

      if (newQty > product.stock) {
        Alert.alert('Stok Terbatas', `Stok maksimum untuk produk ini adalah ${product.stock} ${product.unit}.`);
        return prevCart;
      }

      const updated = [...prevCart];
      updated[existingIndex] = {
        ...item,
        quantity: newQty,
        subtotal: newQty * item.unit_price,
      };
      return updated;
    });
  };

  const removeFromCart = (productId: number) => {
    setCart((prevCart) => prevCart.filter((item) => item.product_id !== productId));
  };

  // 4. Totals Calculation
  const subtotal = useMemo(() => {
    return cart.reduce((sum, item) => sum + item.subtotal, 0);
  }, [cart]);

  const discountAmount = useMemo(() => {
    if (!selectedDiscount) return 0;
    if (selectedDiscount.type === 'percentage') {
      const calculated = (subtotal * selectedDiscount.value) / 100;
      return selectedDiscount.max_discount ? Math.min(calculated, selectedDiscount.max_discount) : calculated;
    } else {
      return Math.min(selectedDiscount.value, subtotal);
    }
  }, [selectedDiscount, subtotal]);

  const taxAmount = useMemo(() => {
    if (!settings || !settings.tax_enabled) return 0;
    const taxableAmount = subtotal - discountAmount;
    return (taxableAmount * settings.tax_rate) / 100;
  }, [settings, subtotal, discountAmount]);

  const totalAmount = useMemo(() => {
    const calculated = subtotal - discountAmount + taxAmount;
    return Math.max(0, calculated);
  }, [subtotal, discountAmount, taxAmount]);

  const changeAmount = useMemo(() => {
    const received = parseFloat(cashReceived) || 0;
    return Math.max(0, received - totalAmount);
  }, [cashReceived, totalAmount]);

  // Suggested cash shortcuts
  const suggestedCashAmounts = useMemo(() => {
    if (totalAmount <= 0) return [];
    const base = Math.ceil(totalAmount / 1000) * 1000;
    const suggestions = [totalAmount, base];
    
    const bills = [10000, 20000, 50000, 100000];
    bills.forEach(bill => {
      if (bill > totalAmount && !suggestions.includes(bill)) {
        suggestions.push(bill);
      }
    });

    return [...new Set(suggestions)].sort((a, b) => a - b).slice(0, 4);
  }, [totalAmount]);

  // 5. Checkout Submit to Laravel Backend
  const handleCheckout = async () => {
    if (cart.length === 0) {
      Alert.alert('Keranjang Kosong', 'Silakan pilih produk terlebih dahulu.');
      return;
    }

    if (paymentMethod === 'cash') {
      const received = parseFloat(cashReceived) || 0;
      if (received < totalAmount) {
        Alert.alert('Uang Kurang', 'Nominal uang tunai yang diterima kurang dari total tagihan.');
        return;
      }
    }

    setIsSubmitting(true);
    try {
      const payload: CreateOrderPayload = {
        payment_method: paymentMethod,
        payment_status: paymentMethod === 'cash' ? 'paid' : 'paid',
        paid_amount: totalAmount,
        discount: discountAmount,
        discount_id: selectedDiscount?.id,
        cash_received: paymentMethod === 'cash' ? parseFloat(cashReceived) : totalAmount,
        items: cart.map((i) => ({
          product_id: i.product_id,
          quantity: i.quantity,
          unit_price: i.unit_price,
          discount: i.discount || 0,
        })),
      };

      const newOrder = await orderApi.create(payload);

      setCompletedOrder({
        orderNumber: newOrder.order_number,
        total: totalAmount,
        change: paymentMethod === 'cash' ? changeAmount : 0,
      });

      // Clear state
      setCart([]);
      setSelectedDiscount(null);
      setCashReceived('');
      setIsCartVisible(false);
      setIsSuccessModalVisible(true);
    } catch (e: any) {
      console.error('Failed to create order', e);
      const msg = e.response?.data?.message || 'Terjadi kesalahan saat memproses transaksi kasir.';
      Alert.alert('Gagal Transaksi', msg);
    } finally {
      setIsSubmitting(false);
    }
  };

  const formatCurrency = (val: any) => {
    const num = parseFloat(val) || 0;
    return `Rp ${num.toLocaleString('id-ID', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`;
  };

  return (
    <SafeAreaView className="flex-1 bg-slate-body">
      {/* 1. Header Area */}
      <View className="bg-white px-6 py-4 flex-row items-center justify-between border-b border-slate-light/10 shadow-sm">
        <View>
          <Text className="text-primary text-xl font-extrabold tracking-tight">
            {settings?.store_name || 'POS Kasir'}
          </Text>
          <Text className="text-slate-sub text-[10px] font-bold">
            KASIR: {user?.name.toUpperCase()}
          </Text>
        </View>
        <TouchableOpacity 
          className="bg-red-50/80 px-4 py-2 rounded-xl border border-red-200"
          onPress={logout}
        >
          <Text className="text-red-500 text-xs font-bold">LOGOUT</Text>
        </TouchableOpacity>
      </View>

      {/* 2. Main Content Grid (Responsive Split Screen for iPad/Tablet) */}
      <View className="flex-1 flex-row">
        {/* Left Side: Product Grid */}
        <View className="flex-1 p-4">
          {/* Search bar & Categories Selector */}
          <View className="mb-4">
            <TextInput
              className="bg-white border border-slate-light/20 rounded-xl px-4 py-3 text-slate-main font-semibold shadow-sm mb-3"
              placeholder="Cari nama produk, SKU, atau scan..."
              placeholderTextColor="#94A3B8"
              value={search}
              onChangeText={setSearch}
            />
            
            {/* Horizontal Categories List */}
            <ScrollView horizontal showsHorizontalScrollIndicator={false} className="flex-row">
              <TouchableOpacity
                className={`px-4 py-2.5 rounded-full mr-2 border ${
                  selectedCategory === null 
                    ? 'bg-primary border-primary shadow-sm shadow-primary-glow' 
                    : 'bg-white border-slate-light/20'
                }`}
                onPress={() => setSelectedCategory(null)}
              >
                <Text className={`text-xs font-extrabold ${selectedCategory === null ? 'text-white' : 'text-slate-sub'}`}>
                  Semua
                </Text>
              </TouchableOpacity>
              {categories.map((c) => (
                <TouchableOpacity
                  key={c.id}
                  className={`px-4 py-2.5 rounded-full mr-2 border ${
                    selectedCategory === c.id 
                      ? 'bg-primary border-primary shadow-sm shadow-primary-glow' 
                      : 'bg-white border-slate-light/20'
                  }`}
                  onPress={() => setSelectedCategory(c.id)}
                >
                  <Text className={`text-xs font-extrabold ${selectedCategory === c.id ? 'text-white' : 'text-slate-sub'}`}>
                    {c.name}
                  </Text>
                </TouchableOpacity>
              ))}
            </ScrollView>
          </View>

          {/* Product Grid List using FlashList (high-performance) */}
          {isLoading ? (
            <View className="flex-1 items-center justify-center">
              <ActivityIndicator size="large" color="#005BFF" />
              <Text className="text-slate-sub text-xs mt-2 font-medium">Memuat katalog kasir...</Text>
            </View>
          ) : filteredProducts.length === 0 ? (
            <View className="flex-1 items-center justify-center">
              <Text className="text-3xl">📦</Text>
              <Text className="text-slate-main font-bold text-base mt-2">Produk Tidak Ditemukan</Text>
              <Text className="text-slate-sub text-xs text-center px-6 mt-1">Coba ketik kata kunci lain atau pilih kategori berbeda.</Text>
            </View>
          ) : (
            <FlashList
              data={filteredProducts}
              numColumns={isTablet ? 3 : 2}
              estimatedItemSize={160}
              renderItem={({ item }) => (
                <TouchableOpacity
                  className="bg-white m-1.5 p-3 rounded-2xl border border-slate-light/10 shadow-sm justify-between relative overflow-hidden"
                  style={{ height: 160 }}
                  onPress={() => addToCart(item)}
                >
                  <View>
                    <Text className="text-slate-main font-extrabold text-sm leading-tight mb-1" numberOfLines={2}>
                      {item.name}
                    </Text>
                    <Text className="text-slate-light text-[10px] font-bold">
                      Stok: {parseFloat(item.stock.toString())} {item.unit}
                    </Text>
                  </View>
                  <View className="flex-row justify-between items-end">
                    <Text className="text-primary font-black text-sm">
                      {formatCurrency(item.price)}
                    </Text>
                    {item.stock <= 3 && (
                      <View className="bg-orange-50 px-2 py-0.5 rounded-full border border-orange-200">
                        <Text className="text-orange-500 text-[8px] font-black">TIPIS</Text>
                      </View>
                    )}
                  </View>
                </TouchableOpacity>
              )}
            />
          )}
        </View>

        {/* Right Side: Cart Sidebar (TABLET ONLY) */}
        {isTablet && (
          <View className="w-[380px] bg-white border-l border-slate-light/10 p-5 justify-between">
            {/* Tablet Cart List */}
            <View className="flex-1">
              <Text className="text-slate-main font-extrabold text-base mb-4">Keranjang Belanja</Text>
              {cart.length === 0 ? (
                <View className="flex-1 items-center justify-center">
                  <Text className="text-2xl">🛒</Text>
                  <Text className="text-slate-light text-xs font-semibold mt-2">Keranjang masih kosong</Text>
                </View>
              ) : (
                <ScrollView className="flex-1">
                  {cart.map((item) => (
                    <View key={item.product_id} className="flex-row items-center justify-between py-3 border-b border-slate-light/5">
                      <View className="flex-1 pr-2">
                        <Text className="text-slate-main font-extrabold text-xs" numberOfLines={1}>{item.product_name}</Text>
                        <Text className="text-slate-light text-[10px] font-bold">{formatCurrency(item.unit_price)} / {item.unit}</Text>
                      </View>
                      <View className="flex-row items-center gap-3">
                        <TouchableOpacity onPress={() => updateQuantity(item.product_id, -1)} className="w-6 h-6 bg-slate-body rounded-lg items-center justify-center">
                          <Text className="text-slate-main font-extrabold text-xs">-</Text>
                        </TouchableOpacity>
                        <Text className="text-slate-main font-black text-xs">{item.quantity}</Text>
                        <TouchableOpacity onPress={() => updateQuantity(item.product_id, 1)} className="w-6 h-6 bg-slate-body rounded-lg items-center justify-center">
                          <Text className="text-slate-main font-extrabold text-xs">+</Text>
                        </TouchableOpacity>
                      </View>
                    </View>
                  ))}
                </ScrollView>
              )}
            </View>

            {/* Tablet Totals & Payment panel */}
            {/* Same calculation UI as phone sheet but integrated */}
            {/* We'll write the unified checkout layout at the bottom */}
          </View>
        )}
      </View>

      {/* 3. Floating Bottom Bar (PHONE ONLY) */}
      {!isTablet && cart.length > 0 && (
        <TouchableOpacity
          className="absolute bottom-24 left-6 right-6 bg-primary rounded-2xl flex-row items-center justify-between px-6 py-4 shadow-lg shadow-primary-glow"
          onPress={() => setIsCartVisible(true)}
        >
          <View>
            <Text className="text-white text-[10px] font-black tracking-wider">KERANJANG BELANJA</Text>
            <Text className="text-white font-extrabold text-sm">{cart.length} item ({formatCurrency(totalAmount)})</Text>
          </View>
          <Text className="text-white font-black text-xs">BAYAR &gt;</Text>
        </TouchableOpacity>
      )}

      {/* 4. Bottom Sheet Modal: Checkout Panel (PHONE ONLY) */}
      <Modal visible={isCartVisible} animationType="slide" transparent>
        <View className="flex-1 bg-slate-main/60 justify-end">
          <SafeAreaView className="bg-white rounded-t-3xl max-h-[90%] p-6">
            <View className="flex-row justify-between items-center mb-4">
              <Text className="text-slate-main font-black text-lg">Nota Belanja</Text>
              <TouchableOpacity onPress={() => setIsCartVisible(false)} className="bg-slate-body px-3 py-1 rounded-full">
                <Text className="text-slate-light font-black text-xs">Tutup</Text>
              </TouchableOpacity>
            </View>

            {/* Scrollable Cart items inside sheet */}
            <ScrollView className="space-y-4 mb-4" style={{ maxHeight: 220 }}>
              {cart.map((item) => (
                <View key={item.product_id} className="flex-row items-center justify-between py-2.5 border-b border-slate-light/5">
                  <View className="flex-1 pr-2">
                    <Text className="text-slate-main font-bold text-sm" numberOfLines={1}>{item.product_name}</Text>
                    <Text className="text-slate-sub text-xs">{formatCurrency(item.unit_price)} x {item.quantity} {item.unit}</Text>
                  </View>
                  <View className="flex-row items-center gap-3">
                    <TouchableOpacity onPress={() => updateQuantity(item.product_id, -1)} className="w-8 h-8 bg-slate-body rounded-xl items-center justify-center border border-slate-light/10">
                      <Text className="text-slate-main font-extrabold text-sm">-</Text>
                    </TouchableOpacity>
                    <Text className="text-slate-main font-extrabold text-sm">{item.quantity}</Text>
                    <TouchableOpacity onPress={() => updateQuantity(item.product_id, 1)} className="w-8 h-8 bg-slate-body rounded-xl items-center justify-center border border-slate-light/10">
                      <Text className="text-slate-main font-extrabold text-sm">+</Text>
                    </TouchableOpacity>
                  </View>
                </View>
              ))}
            </ScrollView>

            {/* Totals panel breakdown */}
            <View className="bg-slate-body rounded-2xl p-4 space-y-2 mb-4">
              <View className="flex-row justify-between">
                <Text className="text-slate-sub text-xs font-semibold">Subtotal</Text>
                <Text className="text-slate-main text-xs font-extrabold">{formatCurrency(subtotal)}</Text>
              </View>
              <TouchableOpacity 
                className="flex-row justify-between"
                onPress={() => setIsDiscountModalVisible(true)}
              >
                <Text className="text-primary text-xs font-extrabold underline">
                  {selectedDiscount ? `Kupon: ${selectedDiscount.name}` : 'Pilih Diskon +'}
                </Text>
                <Text className="text-red-500 text-xs font-extrabold">
                  {discountAmount > 0 ? `-${formatCurrency(discountAmount)}` : 'Rp 0'}
                </Text>
              </TouchableOpacity>
              {settings?.tax_enabled && (
                <View className="flex-row justify-between">
                  <Text className="text-slate-sub text-xs font-semibold">Pajak ({settings.tax_rate}%)</Text>
                  <Text className="text-slate-main text-xs font-extrabold">{formatCurrency(taxAmount)}</Text>
                </View>
              )}
              <View className="flex-row justify-between border-t border-slate-light/10 pt-2 mt-2">
                <Text className="text-slate-main font-black text-sm">TOTAL AKHIR</Text>
                <Text className="text-primary font-black text-base">{formatCurrency(totalAmount)}</Text>
              </View>
            </View>

            {/* Payment Method Selector */}
            <Text className="text-slate-main font-bold text-xs mb-2">METODE PEMBAYARAN</Text>
            <View className="flex-row gap-2 mb-4">
              {['cash', 'transfer', 'qris'].map((m) => (
                <TouchableOpacity
                  key={m}
                  className={`flex-1 py-3 rounded-xl border items-center justify-center ${
                    paymentMethod === m ? 'bg-primary border-primary shadow-sm' : 'bg-white border-slate-light/20'
                  }`}
                  onPress={() => setPaymentMethod(m as any)}
                >
                  <Text className={`text-xs font-extrabold uppercase ${paymentMethod === m ? 'text-white' : 'text-slate-sub'}`}>
                    {m === 'cash' ? '💵 Tunai' : m === 'transfer' ? '🏦 Bank' : '📱 QRIS'}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            {/* Cash Received Inputs (only for Cash) */}
            {paymentMethod === 'cash' && (
              <View className="mb-4">
                <Text className="text-slate-main font-bold text-xs mb-2">UANG TUNAI DITERIMA (Rp)</Text>
                <TextInput
                  className="bg-slate-body border border-slate-light/20 rounded-xl px-4 py-2.5 text-slate-main font-extrabold text-sm"
                  placeholder="Masukkan nominal uang tunai..."
                  keyboardType="numeric"
                  value={cashReceived}
                  onChangeText={setCashReceived}
                />
                {/* Suggested Shortcut buttons */}
                <View className="flex-row gap-2 mt-2">
                  {suggestedCashAmounts.map((amt) => (
                    <TouchableOpacity
                      key={amt}
                      className="bg-slate-body border border-slate-light/10 px-3 py-2 rounded-lg flex-1 items-center"
                      onPress={() => setCashReceived(amt.toString())}
                    >
                      <Text className="text-slate-sub text-[10px] font-black">{formatCurrency(amt)}</Text>
                    </TouchableOpacity>
                  ))}
                </View>
              </View>
            )}

            {/* Change display */}
            {paymentMethod === 'cash' && parseFloat(cashReceived) >= totalAmount && (
              <View className="bg-success/5 border border-success/20 rounded-2xl p-3 flex-row justify-between items-center mb-4">
                <Text className="text-success text-xs font-extrabold">UANG KEMBALIAN</Text>
                <Text className="text-success font-black text-sm">{formatCurrency(changeAmount)}</Text>
              </View>
            )}

            {/* Process payment button */}
            <TouchableOpacity
              className="bg-primary rounded-2xl py-4 items-center justify-center shadow-lg mb-4"
              onPress={handleCheckout}
              disabled={isSubmitting}
            >
              {isSubmitting ? (
                <ActivityIndicator color="#ffffff" />
              ) : (
                <Text className="text-white font-extrabold text-base">PROSES TRANSAKSI &amp; CETAK</Text>
              )}
            </TouchableOpacity>
          </SafeAreaView>
        </View>
      </Modal>

      {/* 5. Discount Kupon Modal Selector */}
      <Modal visible={isDiscountModalVisible} transparent animationType="fade">
        <View className="flex-1 bg-slate-main/50 justify-center px-6">
          <View className="bg-white rounded-3xl p-6 max-h-[60%]">
            <Text className="text-slate-main font-black text-base mb-4 text-center">Pilih Diskon Toko</Text>
            {discounts.length === 0 ? (
              <Text className="text-slate-sub text-center text-xs py-4 font-semibold">Tidak ada kupon diskon aktif.</Text>
            ) : (
              <ScrollView className="space-y-2">
                {discounts.map((disc) => (
                  <TouchableOpacity
                    key={disc.id}
                    className={`p-4 rounded-2xl border mb-2 flex-row justify-between items-center ${
                      selectedDiscount?.id === disc.id ? 'bg-primary/5 border-primary' : 'bg-slate-body border-slate-light/10'
                    }`}
                    onPress={() => {
                      setSelectedDiscount(disc);
                      setIsDiscountModalVisible(false);
                    }}
                  >
                    <View>
                      <Text className="text-slate-main font-extrabold text-sm">{disc.name}</Text>
                      <Text className="text-slate-light text-[10px] font-bold">Min. Belanja: {formatCurrency(disc.min_order)}</Text>
                    </View>
                    <Text className="text-primary font-black text-sm">
                      {disc.type === 'percentage' ? `${disc.value}%` : formatCurrency(disc.value)}
                    </Text>
                  </TouchableOpacity>
                ))}
              </ScrollView>
            )}
            
            <TouchableOpacity 
              onPress={() => {
                setSelectedDiscount(null);
                setIsDiscountModalVisible(false);
              }}
              className="bg-red-50 py-3 rounded-xl border border-red-200 mt-4 items-center"
            >
              <Text className="text-red-500 font-extrabold text-xs">Batalkan Diskon</Text>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>

      {/* 6. Success Struk Pembayaran Modal */}
      <Modal visible={isSuccessModalVisible} transparent animationType="slide">
        <View className="flex-1 bg-slate-main/60 justify-center px-6">
          <View className="bg-white rounded-3xl p-6 items-center shadow-2xl">
            <View className="w-16 h-16 bg-success/10 rounded-full items-center justify-center mb-4">
              <Text className="text-success text-3xl font-bold">✓</Text>
            </View>
            <Text className="text-lg font-black text-slate-main">Transaksi Sukses!</Text>
            <Text className="text-slate-sub text-xs mt-1">Invoice: {completedOrder?.orderNumber}</Text>

            <View className="bg-slate-body rounded-2xl p-4 w-full my-6 space-y-2 border border-slate-light/10">
              <View className="flex-row justify-between">
                <Text className="text-slate-sub text-xs font-semibold">Total Tagihan</Text>
                <Text className="text-slate-main text-xs font-extrabold">{formatCurrency(completedOrder?.total || 0)}</Text>
              </View>
              <View className="flex-row justify-between border-t border-slate-light/5 pt-2">
                <Text className="text-success text-xs font-extrabold">Uang Kembalian</Text>
                <Text className="text-success text-sm font-black">{formatCurrency(completedOrder?.change || 0)}</Text>
              </View>
            </View>

            <View className="flex-row gap-2 w-full">
              <TouchableOpacity
                className="bg-slate-body border border-slate-light/20 py-3 rounded-xl flex-1 items-center justify-center"
                onPress={() => {
                  setIsSuccessModalVisible(false);
                  setCompletedOrder(null);
                }}
              >
                <Text className="text-slate-sub font-extrabold text-xs">Transaksi Baru</Text>
              </TouchableOpacity>
              <TouchableOpacity
                className="bg-primary py-3 rounded-xl flex-1 items-center justify-center shadow-sm shadow-primary-glow"
                onPress={() => {
                  Alert.alert('Cetak Struk', 'Fitur cetak Bluetooth thermal printer terhubung sukses!');
                }}
              >
                <Text className="text-white font-extrabold text-xs">Cetak Struk 🖨️</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};
