import { useAuth } from "@/contexts/AuthContext";
import { obterCorridas } from "@/services/db";
import React, { useCallback, useEffect, useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import Historico from "./historico";
import Lancamento, { type Corrida } from "./lancamento";

export default function Corrida() {
  const { user } = useAuth();
  const [activeTab, setActiveTab] = useState<"lancamento" | "historico">(
    "lancamento",
  );
  const [historico, setHistorico] = useState<Corrida[]>([]);

  const loadHistorico = useCallback(async () => {
    if (!user?.id) return;
    try {
      const corridasDB = await obterCorridas(user.id);
      setHistorico(
        corridasDB.map((c) => ({
          id: c.id,
          data: c.data,
          empresa: c.empresa,
          km: c.km,
          custoPorKm: c.custo_por_km,
          total: c.total,
          usuario: user.email,
        })),
      );
    } catch (error) {
      console.error("Erro ao carregar histórico:", error);
    }
  }, [user?.id, user?.email]);

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

  const handleLancarCorrida = async (_corrida: Corrida) => {
    await loadHistorico();
    setActiveTab("historico");
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.tabsContainer}>
        <TouchableOpacity
          style={[styles.tab, activeTab === "lancamento" && styles.tabActive]}
          onPress={() => setActiveTab("lancamento")}
        >
          <Text
            style={[
              styles.tabLabel,
              activeTab === "lancamento" && styles.tabLabelActive,
            ]}
          >
            📍 Lançar
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          style={[styles.tab, activeTab === "historico" && styles.tabActive]}
          onPress={() => setActiveTab("historico")}
        >
          <Text
            style={[
              styles.tabLabel,
              activeTab === "historico" && styles.tabLabelActive,
            ]}
          >
            📋 Histórico
          </Text>
        </TouchableOpacity>
      </View>

      <View style={styles.content}>
        {activeTab === "lancamento" ? (
          <Lancamento onLancar={handleLancarCorrida} />
        ) : (
          <Historico historico={historico} />
        )}
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#ffffff",
  },
  tabsContainer: {
    flexDirection: "row",
    backgroundColor: "#ffffff",
    borderBottomWidth: 2,
    borderBottomColor: "#000000",
  },
  tab: {
    flex: 1,
    paddingVertical: 16,
    justifyContent: "center",
    alignItems: "center",
    borderBottomWidth: 3,
    borderBottomColor: "transparent",
  },
  tabActive: {
    borderBottomColor: "#000000",
  },
  tabLabel: {
    fontSize: 14,
    fontWeight: "600",
    color: "#666666",
  },
  tabLabelActive: {
    color: "#000000",
  },
  content: {
    flex: 1,
  },
});
