import { Button } from "@/components/Button";
import { Input } from "@/components/Input";
import { Select } from "@/components/Select";
import { BORDER_RADIUS, COLORS, SPACING } from "@/constants/theme";
import { useAuth } from "@/contexts/AuthContext";
import { CompanyDB, obterEmpresas, salvarCorrida } from "@/services/db";
import { router, useFocusEffect } from "expo-router";
import React, { useCallback, useState } from "react";
import {
  Alert,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export type Corrida = {
  id: string;
  data: string;
  empresa: string;
  km: number;
  custoPorKm: number;
  total: number;
  usuario: string;
};

export default function LancamentoPage() {
  const { user } = useAuth();
  const [empresasDB, setEmpresasDB] = useState<CompanyDB[]>([]);
  const [empresaId, setEmpresaId] = useState("");
  const [custoPorKm, setCustoPorKm] = useState(0);
  const [distancia, setDistancia] = useState("");
  const [loading, setLoading] = useState(false);

  const distanciaNum = parseFloat(distancia) || 0;
  const totalCorrida = distanciaNum * custoPorKm;

  useFocusEffect(
    useCallback(() => {
      obterEmpresas()
        .then(setEmpresasDB)
        .catch(() => Alert.alert("Erro", "Não foi possível carregar as empresas."));
    }, []),
  );

  const empresasItems = [
    { label: "Selecione uma empresa", value: "" },
    ...empresasDB.map((e) => ({ label: e.name, value: e.id })),
  ];

  const handleEmpresaChange = (id: string) => {
    setEmpresaId(id);
    const found = empresasDB.find((e) => e.id === id);
    setCustoPorKm(found?.cost_per_km ?? 0);
  };

  const handleLancarCorrida = async () => {
    if (!empresaId) {
      Alert.alert("Validação", "Por favor, selecione uma empresa.");
      return;
    }
    if (!distancia || distanciaNum <= 0) {
      Alert.alert("Validação", "Por favor, insira uma distância válida.");
      return;
    }

    const empresaSelecionada = empresasDB.find((e) => e.id === empresaId);

    try {
      setLoading(true);
      await salvarCorrida({
        id: Date.now().toString(),
        user_id: user?.id ?? "",
        company: empresaSelecionada?.name ?? empresaId,
        km: distanciaNum,
        cost_per_km: custoPorKm,
        total: totalCorrida,
        ride_date: new Date().toLocaleString("pt-BR"),
        synced: 0,
      });
      setEmpresaId("");
      setCustoPorKm(0);
      setDistancia("");
      Alert.alert("Sucesso", "Corrida registrada com sucesso!", [
        { text: "OK", onPress: () => router.back() },
      ]);
    } catch (error) {
      console.error("Erro ao salvar corrida:", error);
      Alert.alert("Erro", "Não foi possível registrar a corrida.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => router.back()} style={styles.backButton} activeOpacity={0.7}>
          <Text style={styles.backIcon}>←</Text>
          <Text style={styles.backLabel}>Voltar</Text>
        </TouchableOpacity>
      </View>

      <KeyboardAvoidingView
        style={{ flex: 1 }}
        behavior={Platform.select({ ios: "padding", android: "height" })}
      >
        <ScrollView
          contentContainerStyle={styles.scrollContent}
          showsVerticalScrollIndicator={false}
        >
          <View style={styles.titleSection}>
            <Text style={styles.title}>Nova Corrida</Text>
            <Text style={styles.subtitle}>Preencha os dados abaixo</Text>
          </View>

          <View style={styles.card}>
            <Text style={styles.cardLabel}>Empresa</Text>
            <Select value={empresaId} onValueChange={handleEmpresaChange} items={empresasItems} />
          </View>

          <View style={styles.card}>
            <Text style={styles.cardLabel}>Distância (km)</Text>
            <Input
              placeholder="Digite a distância"
              keyboardType="decimal-pad"
              value={distancia}
              onChangeText={setDistancia}
            />
          </View>

          <View style={styles.card}>
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>Custo por km</Text>
              <Text style={styles.infoValue}>R$ {custoPorKm.toFixed(2)}</Text>
            </View>
          </View>

          <View style={[styles.card, styles.totalCard]}>
            <Text style={styles.totalLabel}>Valor Total</Text>
            <Text style={styles.totalAmount}>R$ {totalCorrida.toFixed(2)}</Text>
          </View>

          <Button
            label={loading ? "Salvando..." : "Lançar Corrida"}
            onPress={handleLancarCorrida}
            disabled={loading}
          />
        </ScrollView>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  header: {
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  backButton: {
    flexDirection: "row",
    alignItems: "center",
    gap: SPACING.xs,
    alignSelf: "flex-start",
  },
  backIcon: {
    fontSize: 18,
    color: COLORS.text,
  },
  backLabel: {
    fontSize: 15,
    color: COLORS.textSecondary,
    fontWeight: "500",
  },
  scrollContent: {
    padding: SPACING.lg,
    paddingBottom: SPACING.xxl,
  },
  titleSection: {
    marginBottom: SPACING.xl,
    marginTop: SPACING.md,
  },
  title: {
    fontSize: 28,
    fontWeight: "800",
    color: COLORS.text,
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 14,
    color: COLORS.textTertiary,
  },
  card: {
    backgroundColor: COLORS.surface,
    borderRadius: BORDER_RADIUS.lg,
    padding: SPACING.lg,
    marginBottom: SPACING.md,
    borderWidth: 1,
    borderColor: COLORS.border,
  },
  cardLabel: {
    fontSize: 11,
    fontWeight: "700",
    color: COLORS.textTertiary,
    marginBottom: SPACING.sm,
    textTransform: "uppercase",
    letterSpacing: 0.8,
  },
  infoRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  infoLabel: {
    fontSize: 14,
    color: COLORS.textSecondary,
    fontWeight: "500",
  },
  infoValue: {
    fontSize: 16,
    fontWeight: "700",
    color: COLORS.text,
  },
  totalCard: {
    borderColor: COLORS.borderLight,
    borderLeftWidth: 3,
    borderLeftColor: COLORS.success,
    marginBottom: SPACING.xl,
  },
  totalLabel: {
    fontSize: 12,
    color: COLORS.textTertiary,
    fontWeight: "600",
    textTransform: "uppercase",
    letterSpacing: 0.5,
    marginBottom: SPACING.xs,
  },
  totalAmount: {
    fontSize: 32,
    fontWeight: "800",
    color: COLORS.success,
  },
});
