import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, ActivityIndicator, Alert, SafeAreaView } from 'react-native';
import { dashboardApi, settingsApi } from '../lib/api';
import { useAuth } from '../context/AuthContext';
import type { DashboardStats } from '../types';

export const DashboardScreen: React.FC = () => {
  const { user } = useAuth();
  const [isLoading, setIsLoading] = useState(true);
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [storeName, setStoreName] = useState('WALON STORE');

  // Load dashboard stats & store name
  const loadDashboardData = async () => {
    setIsLoading(true);
    try {
      const [statsData, settingsData] = await Promise.all([
        dashboardApi.getStats(),
        settingsApi.getAll()
      ]);
      setStats(statsData || null);
      if (settingsData && settingsData.store_name) {
        setStoreName(settingsData.store_name);
      }
    } catch (e) {
      console.error('Failed to load dashboard statistics', e);
      // Fail silently or fallback to default
    } finally {
      setIsLoading(false);
    }
  };

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

  // Helpers for dynamic greeting & date
  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 11) return 'Selamat Pagi';
    if (hour < 15) return 'Selamat Siang';
    if (hour < 19) return 'Selamat Sore';
    return 'Selamat Malam';
  };

  const getFormattedDate = () => {
    const options: Intl.DateTimeFormatOptions = {
      weekday: 'long',
      day: 'numeric',
      month: 'long',
      year: 'numeric',
    };
    return new Date().toLocaleDateString('id-ID', options);
  };

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

  const getInitial = (name?: string) => {
    if (!name) return 'W';
    return name.charAt(0).toUpperCase();
  };

  return (
    <SafeAreaView className="flex-1 bg-slate-body">
      {/* 1. Header Row (Exactly matching web topbar) */}
      <View className="bg-white px-6 py-4 flex-row items-center justify-between border-b border-slate-light/10 shadow-sm mt-1">
        <View className="flex-row items-center gap-3">
          {/* Hamburger Menu Icon */}
          <Text className="text-slate-main text-2xl font-bold">☰</Text>
          <Text className="text-slate-main text-base font-extrabold">{getGreeting()}</Text>
        </View>
        
        {/* Profile Circle Avatar matching 'W' */}
        <View className="w-10 h-10 bg-primary rounded-full items-center justify-center border-2 border-primary-light shadow-md shadow-primary-glow">
          <Text className="text-white text-base font-black">
            {getInitial(storeName)}
          </Text>
        </View>
      </View>

      {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">Menyusun dashboard kasir...</Text>
        </View>
      ) : (
        <ScrollView className="flex-1 p-5 space-y-4">
          <Text className="text-slate-main font-black text-xl mb-1 tracking-tight">Dashboard</Text>

          {/* 2. Banner Card (Blue Gradient Card matching screenshot 100%) */}
          <View className="bg-primary rounded-3xl p-6 shadow-lg shadow-primary-glow border border-primary-hover relative overflow-hidden mb-4">
            {/* Ambient Background Circles */}
            <View className="absolute -top-12 -right-12 w-36 h-36 bg-white/5 rounded-full" />
            <View className="absolute -bottom-10 -left-10 w-24 h-24 bg-white/5 rounded-full" />
            
            <Text className="text-white text-2xl font-black leading-tight tracking-tight">
              {getGreeting()}, {storeName.toUpperCase()}
            </Text>
            <Text className="text-white/80 text-xs font-semibold mt-2">
              {getFormattedDate()}
            </Text>
          </View>

          {/* 3. Summary Card 1: Pendapatan Hari Ini */}
          <View className="bg-white rounded-3xl p-5 border border-slate-light/10 shadow-sm flex-row items-center gap-4 mb-4">
            <View className="w-12 h-12 bg-primary/10 rounded-2xl items-center justify-center border border-primary/20">
              <Text className="text-primary text-xl font-bold">💵</Text>
            </View>
            <View className="flex-1">
              <Text className="text-slate-sub text-[11px] font-bold uppercase tracking-wide">Pendapatan Hari Ini</Text>
              <Text className="text-slate-main font-black text-lg mt-0.5">
                {formatCurrency(stats?.today_revenue || 0)}
              </Text>
              <Text className="text-slate-light text-[10px] font-bold mt-1">
                {stats?.today_orders || 0} transaksi selesai
              </Text>
            </View>
          </View>

          {/* 4. Summary Card 2: Laba Hari Ini */}
          <View className="bg-white rounded-3xl p-5 border border-slate-light/10 shadow-sm flex-row items-center gap-4 mb-4">
            <View className="w-12 h-12 bg-success/10 rounded-2xl items-center justify-center border border-success/20">
              <Text className="text-success text-xl font-bold">📈</Text>
            </View>
            <View className="flex-1">
              <Text className="text-slate-sub text-[11px] font-bold uppercase tracking-wide">Laba Hari Ini</Text>
              <Text className="text-success font-black text-lg mt-0.5">
                {formatCurrency(stats?.today_profit || 0)}
              </Text>
              <Text className="text-slate-light text-[10px] font-bold mt-1">
                Modal: {formatCurrency(Math.max(0, (stats?.today_revenue || 0) - (stats?.today_profit || 0)))}
              </Text>
            </View>
          </View>

          {/* 5. Summary Card 3: Pesanan Hari Ini */}
          <View className="bg-white rounded-3xl p-5 border border-slate-light/10 shadow-sm flex-row items-center gap-4 mb-4">
            <View className="w-12 h-12 bg-amber-500/10 rounded-2xl items-center justify-center border border-amber-500/20">
              <Text className="text-amber-500 text-xl font-bold">🛒</Text>
            </View>
            <View className="flex-1">
              <Text className="text-slate-sub text-[11px] font-bold uppercase tracking-wide">Pesanan Hari Ini</Text>
              <Text className="text-slate-main font-black text-lg mt-0.5">
                {stats?.today_orders || 0}
              </Text>
              <Text className="text-slate-light text-[10px] font-bold mt-1">
                {stats && stats.today_orders > 0 ? `${stats.today_orders} penjualan terdaftar` : 'Belum ada penjualan'}
              </Text>
            </View>
          </View>

          {/* 6. Summary Card 4: Piutang */}
          <View className="bg-white rounded-3xl p-5 border border-slate-light/10 shadow-sm flex-row items-center gap-4 mb-4">
            <View className="w-12 h-12 bg-red-500/10 rounded-2xl items-center justify-center border border-red-500/20">
              <Text className="text-red-500 text-xl font-bold">📄</Text>
            </View>
            <View className="flex-1">
              <Text className="text-slate-sub text-[11px] font-bold uppercase tracking-wide">Piutang Pelanggan</Text>
              <Text className="text-red-500 font-black text-lg mt-0.5">
                Rp 0
              </Text>
              <Text className="text-slate-light text-[10px] font-bold mt-1">
                Semua piutang pelanggan lunas
              </Text>
            </View>
          </View>

          <View className="h-24" />
        </ScrollView>
      )}
    </SafeAreaView>
  );
};
