import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, ActivityIndicator, Alert, TouchableOpacity, Modal, SafeAreaView } from 'react-native';
import { orderApi } from '../lib/api';
import type { Order } from '../types';

export const HistoryScreen: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [orders, setOrders] = useState<Order[]>([]);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);

  const loadOrderHistory = async () => {
    setIsLoading(true);
    try {
      const res = await orderApi.getAll({ page: 1, per_page: 20 });
      setOrders(res.data || []);
    } catch (e) {
      console.error('Failed to load orders history', e);
      Alert.alert('Gagal Memuat', 'Tidak dapat mengambil riwayat transaksi dari server.');
    } finally {
      setIsLoading(false);
    }
  };

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

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

  return (
    <SafeAreaView className="flex-1 bg-slate-body">
      {/* Header */}
      <View className="bg-white px-6 py-4 border-b border-slate-light/10 shadow-sm flex-row justify-between items-center">
        <View>
          <Text className="text-slate-main text-lg font-black tracking-tight">Riwayat Transaksi</Text>
          <Text className="text-slate-light text-[10px] font-bold">20 INVOICE TERBARU CLOUD</Text>
        </View>
        <TouchableOpacity onPress={loadOrderHistory} className="bg-primary/10 px-3 py-1.5 rounded-full">
          <Text className="text-primary text-[10px] font-black">REFRESH 🔄</Text>
        </TouchableOpacity>
      </View>

      {/* Main List */}
      {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 riwayat invoice...</Text>
        </View>
      ) : orders.length === 0 ? (
        <View className="flex-1 items-center justify-center p-6">
          <Text className="text-3xl">📜</Text>
          <Text className="text-slate-main font-bold text-base mt-2">Belum Ada Transaksi</Text>
          <Text className="text-slate-sub text-xs text-center mt-1">Lakukan penjualan perdana di halaman Kasir untuk melihat riwayat belanja di sini.</Text>
        </View>
      ) : (
        <ScrollView className="flex-1 p-4 space-y-3">
          {orders.map((ord) => (
            <TouchableOpacity
              key={ord.id}
              className="bg-white p-4 rounded-2xl border border-slate-light/10 shadow-sm flex-row justify-between items-center mb-3"
              onPress={() => setSelectedOrder(ord)}
            >
              <View className="space-y-1">
                <Text className="text-slate-main font-extrabold text-xs">{ord.order_number}</Text>
                <Text className="text-slate-light text-[10px] font-bold">
                  {new Date(ord.created_at).toLocaleDateString('id-ID', {
                    day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit'
                  })}
                </Text>
                <View className="flex-row gap-1.5 mt-1">
                  <View className="bg-primary/5 px-2 py-0.5 rounded-md border border-primary/15">
                    <Text className="text-primary text-[8px] font-black uppercase">{ord.payment_method}</Text>
                  </View>
                  <View className="bg-success/5 px-2 py-0.5 rounded-md border border-success/15">
                    <Text className="text-success text-[8px] font-black uppercase">{ord.status}</Text>
                  </View>
                </View>
              </View>
              <Text className="text-slate-main font-black text-sm">{formatCurrency(ord.total)}</Text>
            </TouchableOpacity>
          ))}
          <View className="h-16" />
        </ScrollView>
      )}

      {/* Invoice Detail Modal */}
      <Modal visible={!!selectedOrder} animationType="slide" transparent>
        <View className="flex-1 bg-slate-main/60 justify-end">
          <SafeAreaView className="bg-white rounded-t-3xl max-h-[85%] p-6">
            <View className="flex-row justify-between items-center mb-6">
              <Text className="text-slate-main font-black text-base">Detail Invoice</Text>
              <TouchableOpacity onPress={() => setSelectedOrder(null)} className="bg-slate-body px-3 py-1 rounded-full">
                <Text className="text-slate-light font-black text-xs">Tutup</Text>
              </TouchableOpacity>
            </View>

            {selectedOrder && (
              <ScrollView className="space-y-4">
                {/* Branding block */}
                <View className="items-center pb-4 border-b border-slate-light/10">
                  <Text className="text-primary font-black text-base">POS KASIR RECEIPT</Text>
                  <Text className="text-slate-light text-[10px] font-bold mt-1">NO: {selectedOrder.order_number}</Text>
                </View>

                {/* Items loop */}
                <View className="space-y-3">
                  <Text className="text-slate-main font-bold text-xs">BARANG BELANJA</Text>
                  {selectedOrder.items && selectedOrder.items.map((it, idx) => (
                    <View key={idx} className="flex-row justify-between py-1 border-b border-slate-light/5">
                      <View className="flex-1 pr-2">
                        <Text className="text-slate-main font-bold text-xs" numberOfLines={1}>{it.product_name}</Text>
                        <Text className="text-slate-light text-[10px] font-semibold">{formatCurrency(it.unit_price)} x {it.quantity}</Text>
                      </View>
                      <Text className="text-slate-main font-extrabold text-xs">{formatCurrency(it.subtotal)}</Text>
                    </View>
                  ))}
                </View>

                {/* Totals panel breakdown */}
                <View className="bg-slate-body rounded-2xl p-4 space-y-2 mt-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(selectedOrder.subtotal)}</Text>
                  </View>
                  {selectedOrder.discount > 0 && (
                    <View className="flex-row justify-between">
                      <Text className="text-red-500 text-xs font-bold">Diskon Potongan</Text>
                      <Text className="text-red-500 text-xs font-extrabold">-{formatCurrency(selectedOrder.discount)}</Text>
                    </View>
                  )}
                  {selectedOrder.tax > 0 && (
                    <View className="flex-row justify-between">
                      <Text className="text-slate-sub text-xs font-semibold">Pajak Pertambahan</Text>
                      <Text className="text-slate-main text-xs font-extrabold">{formatCurrency(selectedOrder.tax)}</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 BELANJA</Text>
                    <Text className="text-primary font-black text-base">{formatCurrency(selectedOrder.total)}</Text>
                  </View>
                </View>

                {/* Reprint button */}
                <TouchableOpacity
                  className="bg-primary rounded-2xl py-4 items-center justify-center shadow-lg my-4"
                  onPress={() => Alert.alert('Cetak Struk', 'Mencetak ulang struk thermal Bluetooth berhasil!')}
                >
                  <Text className="text-white font-extrabold text-xs">CETAK ULANG STRUK 🖨️</Text>
                </TouchableOpacity>
              </ScrollView>
            )}
          </SafeAreaView>
        </View>
      </Modal>
    </SafeAreaView>
  );
};
