import { Input } from "@/components/Input";
import { BORDER_RADIUS, COLORS, SPACING } from "@/constants/theme";
import {
  CompanyDB,
  atualizarEmpresa,
  deletarEmpresa,
  obterEmpresas,
  salvarEmpresa,
} from "@/services/db";
import { router, useFocusEffect } from "expo-router";
import React, { useCallback, useState } from "react";
import {
  Alert,
  FlatList,
  KeyboardAvoidingView,
  Modal,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

type FormState = {
  nome: string;
  custoPorKm: string;
  observacoes: string;
};

const FORM_VAZIO: FormState = { nome: "", custoPorKm: "", observacoes: "" };

export default function EmpresasPage() {
  const [empresas, setEmpresas] = useState<CompanyDB[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editando, setEditando] = useState<CompanyDB | null>(null);
  const [form, setForm] = useState<FormState>(FORM_VAZIO);
  const [loading, setLoading] = useState(false);

  const loadEmpresas = useCallback(async () => {
    try {
      setEmpresas(await obterEmpresas());
    } catch {
      Alert.alert("Erro", "Não foi possível carregar as empresas.");
    }
  }, []);

  useFocusEffect(useCallback(() => { loadEmpresas(); }, [loadEmpresas]));

  const abrirAdicionar = () => {
    setEditando(null);
    setForm(FORM_VAZIO);
    setModalVisible(true);
  };

  const abrirEditar = (empresa: CompanyDB) => {
    setEditando(empresa);
    setForm({
      nome: empresa.name,
      custoPorKm: empresa.cost_per_km.toString(),
      observacoes: empresa.notes ?? "",
    });
    setModalVisible(true);
  };

  const fecharModal = () => {
    setModalVisible(false);
    setEditando(null);
    setForm(FORM_VAZIO);
  };

  const handleSalvar = async () => {
    const nomeTrimmed = form.nome.trim();
    const custo = parseFloat(form.custoPorKm.replace(",", "."));

    if (!nomeTrimmed) {
      Alert.alert("Validação", "Informe o nome da empresa.");
      return;
    }
    if (isNaN(custo) || custo <= 0) {
      Alert.alert("Validação", "Informe um custo por km válido.");
      return;
    }

    try {
      setLoading(true);
      if (editando) {
        await atualizarEmpresa({
          id: editando.id,
          name: nomeTrimmed,
          cost_per_km: custo,
          notes: form.observacoes.trim(),
        });
      } else {
        await salvarEmpresa({
          id: Date.now().toString(),
          name: nomeTrimmed,
          cost_per_km: custo,
          notes: form.observacoes.trim(),
        });
      }
      await loadEmpresas();
      fecharModal();
    } catch {
      Alert.alert("Erro", "Não foi possível salvar a empresa.");
    } finally {
      setLoading(false);
    }
  };

  const handleDeletar = (empresa: CompanyDB) => {
    Alert.alert(
      "Excluir empresa",
      `Deseja excluir "${empresa.name}"? Esta ação não pode ser desfeita.`,
      [
        { text: "Cancelar", style: "cancel" },
        {
          text: "Excluir",
          style: "destructive",
          onPress: async () => {
            try {
              await deletarEmpresa(empresa.id);
              await loadEmpresas();
            } catch {
              Alert.alert("Erro", "Não foi possível excluir a empresa.");
            }
          },
        },
      ],
    );
  };

  const renderItem = ({ item, index }: { item: CompanyDB; index: number }) => (
    <View style={styles.item}>
      <View style={styles.itemLeft}>
        <View style={styles.itemIndex}>
          <Text style={styles.itemIndexText}>{index + 1}</Text>
        </View>
        <View style={styles.itemInfo}>
          <Text style={styles.itemNome}>{item.name}</Text>
          <Text style={styles.itemCusto}>R$ {item.cost_per_km.toFixed(2)} / km</Text>
          {item.notes ? (
            <Text style={styles.itemObs} numberOfLines={1}>
              {item.notes}
            </Text>
          ) : null}
        </View>
      </View>
      <View style={styles.itemActions}>
        <TouchableOpacity
          style={[styles.actionBtn, styles.editBtn]}
          onPress={() => abrirEditar(item)}
          activeOpacity={0.7}
        >
          <Text style={styles.actionBtnText}>✏️</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={[styles.actionBtn, styles.deleteBtn]}
          onPress={() => handleDeletar(item)}
          activeOpacity={0.7}
        >
          <Text style={styles.actionBtnText}>🗑️</Text>
        </TouchableOpacity>
      </View>
    </View>
  );

  return (
    <SafeAreaView style={styles.container}>
      {/* Header */}
      <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>
        <TouchableOpacity
          style={styles.addButton}
          onPress={abrirAdicionar}
          activeOpacity={0.8}
        >
          <Text style={styles.addButtonText}>+ Adicionar</Text>
        </TouchableOpacity>
      </View>

      {/* Title */}
      <View style={styles.titleSection}>
        <Text style={styles.title}>Empresas</Text>
        <Text style={styles.subtitle}>
          {empresas.length} empresa{empresas.length !== 1 ? "s" : ""} cadastrada{empresas.length !== 1 ? "s" : ""}
        </Text>
      </View>

      {/* Lista */}
      {empresas.length === 0 ? (
        <ScrollView contentContainerStyle={styles.emptyContainer}>
          <Text style={styles.emptyEmoji}>🏢</Text>
          <Text style={styles.emptyTitle}>Nenhuma empresa cadastrada</Text>
          <Text style={styles.emptyText}>
            Toque em "+ Adicionar" para cadastrar a primeira empresa.
          </Text>
        </ScrollView>
      ) : (
        <FlatList
          data={empresas}
          keyExtractor={(item) => item.id}
          renderItem={renderItem}
          contentContainerStyle={styles.listContent}
          showsVerticalScrollIndicator={false}
        />
      )}

      {/* Modal Add/Edit */}
      <Modal
        visible={modalVisible}
        animationType="slide"
        transparent
        onRequestClose={fecharModal}
      >
        <KeyboardAvoidingView
          style={styles.modalOverlay}
          behavior={Platform.select({ ios: "padding", android: "height" })}
        >
          <View style={styles.modalSheet}>
            <View style={styles.modalHandle} />

            <View style={styles.modalHeader}>
              <Text style={styles.modalTitle}>
                {editando ? "Editar Empresa" : "Nova Empresa"}
              </Text>
              <TouchableOpacity onPress={fecharModal} activeOpacity={0.7}>
                <Text style={styles.modalClose}>✕</Text>
              </TouchableOpacity>
            </View>

            <ScrollView showsVerticalScrollIndicator={false}>
              <View style={styles.formGroup}>
                <Text style={styles.formLabel}>Nome da Empresa</Text>
                <Input
                  placeholder="Ex: MULTI B"
                  value={form.nome}
                  onChangeText={(v) => setForm((f) => ({ ...f, nome: v }))}
                  autoCapitalize="characters"
                />
              </View>

              <View style={styles.formGroup}>
                <Text style={styles.formLabel}>Custo por km (R$)</Text>
                <Input
                  placeholder="Ex: 2.70"
                  keyboardType="decimal-pad"
                  value={form.custoPorKm}
                  onChangeText={(v) => setForm((f) => ({ ...f, custoPorKm: v }))}
                />
              </View>

              <View style={styles.formGroup}>
                <Text style={styles.formLabel}>Observações (opcional)</Text>
                <Input
                  placeholder="Ex: Pagamento quinzenal"
                  value={form.observacoes}
                  onChangeText={(v) => setForm((f) => ({ ...f, observacoes: v }))}
                />
              </View>

              <TouchableOpacity
                style={[styles.saveButton, loading && styles.saveButtonDisabled]}
                onPress={handleSalvar}
                disabled={loading}
                activeOpacity={0.8}
              >
                <Text style={styles.saveButtonText}>
                  {loading ? "Salvando..." : editando ? "Salvar alterações" : "Cadastrar empresa"}
                </Text>
              </TouchableOpacity>
            </ScrollView>
          </View>
        </KeyboardAvoidingView>
      </Modal>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },

  // Header
  header: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingHorizontal: SPACING.lg,
    paddingVertical: SPACING.md,
    borderBottomWidth: 1,
    borderBottomColor: COLORS.border,
  },
  backButton: {
    flexDirection: "row",
    alignItems: "center",
    gap: SPACING.xs,
  },
  backIcon: {
    fontSize: 18,
    color: COLORS.text,
  },
  backLabel: {
    fontSize: 15,
    color: COLORS.textSecondary,
    fontWeight: "500",
  },
  addButton: {
    backgroundColor: COLORS.surface,
    borderWidth: 1,
    borderColor: COLORS.borderLight,
    paddingHorizontal: SPACING.md,
    paddingVertical: SPACING.sm,
    borderRadius: BORDER_RADIUS.md,
  },
  addButtonText: {
    fontSize: 13,
    fontWeight: "700",
    color: COLORS.text,
  },

  // Title
  titleSection: {
    paddingHorizontal: SPACING.lg,
    paddingTop: SPACING.lg,
    paddingBottom: SPACING.md,
  },
  title: {
    fontSize: 28,
    fontWeight: "800",
    color: COLORS.text,
    marginBottom: 4,
  },
  subtitle: {
    fontSize: 13,
    color: COLORS.textTertiary,
  },

  // List
  listContent: {
    padding: SPACING.lg,
    paddingBottom: SPACING.xxl,
  },
  item: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    backgroundColor: COLORS.surface,
    borderRadius: BORDER_RADIUS.lg,
    marginBottom: SPACING.sm,
    padding: SPACING.md,
    borderWidth: 1,
    borderColor: COLORS.border,
  },
  itemLeft: {
    flexDirection: "row",
    alignItems: "center",
    flex: 1,
    gap: SPACING.md,
  },
  itemIndex: {
    width: 32,
    height: 32,
    borderRadius: BORDER_RADIUS.round,
    backgroundColor: COLORS.surfaceLight,
    justifyContent: "center",
    alignItems: "center",
  },
  itemIndexText: {
    fontSize: 12,
    fontWeight: "700",
    color: COLORS.textTertiary,
  },
  itemInfo: {
    flex: 1,
  },
  itemNome: {
    fontSize: 15,
    fontWeight: "700",
    color: COLORS.text,
    marginBottom: 2,
  },
  itemCusto: {
    fontSize: 13,
    color: COLORS.success,
    fontWeight: "600",
  },
  itemObs: {
    fontSize: 11,
    color: COLORS.textTertiary,
    marginTop: 2,
  },
  itemActions: {
    flexDirection: "row",
    gap: SPACING.xs,
  },
  actionBtn: {
    width: 36,
    height: 36,
    borderRadius: BORDER_RADIUS.md,
    justifyContent: "center",
    alignItems: "center",
    borderWidth: 1,
  },
  editBtn: {
    backgroundColor: COLORS.surfaceLight,
    borderColor: COLORS.border,
  },
  deleteBtn: {
    backgroundColor: COLORS.surfaceLight,
    borderColor: COLORS.border,
  },
  actionBtnText: {
    fontSize: 15,
  },

  // Empty
  emptyContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: SPACING.lg,
  },
  emptyEmoji: {
    fontSize: 48,
    marginBottom: SPACING.lg,
  },
  emptyTitle: {
    fontSize: 18,
    fontWeight: "700",
    color: COLORS.text,
    marginBottom: SPACING.sm,
    textAlign: "center",
  },
  emptyText: {
    fontSize: 14,
    color: COLORS.textTertiary,
    textAlign: "center",
    lineHeight: 20,
  },

  // Modal
  modalOverlay: {
    flex: 1,
    justifyContent: "flex-end",
    backgroundColor: "rgba(0,0,0,0.7)",
  },
  modalSheet: {
    backgroundColor: COLORS.surface,
    borderTopLeftRadius: 24,
    borderTopRightRadius: 24,
    padding: SPACING.lg,
    paddingBottom: SPACING.xxl,
    borderTopWidth: 1,
    borderColor: COLORS.border,
    maxHeight: "85%",
  },
  modalHandle: {
    width: 40,
    height: 4,
    borderRadius: 2,
    backgroundColor: COLORS.border,
    alignSelf: "center",
    marginBottom: SPACING.lg,
  },
  modalHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: SPACING.xl,
  },
  modalTitle: {
    fontSize: 20,
    fontWeight: "800",
    color: COLORS.text,
  },
  modalClose: {
    fontSize: 18,
    color: COLORS.textTertiary,
    padding: SPACING.xs,
  },

  // Form
  formGroup: {
    marginBottom: SPACING.lg,
  },
  formLabel: {
    fontSize: 11,
    fontWeight: "700",
    color: COLORS.textTertiary,
    textTransform: "uppercase",
    letterSpacing: 0.8,
    marginBottom: SPACING.sm,
  },
  saveButton: {
    backgroundColor: COLORS.text,
    borderRadius: BORDER_RADIUS.lg,
    paddingVertical: SPACING.lg,
    alignItems: "center",
    marginTop: SPACING.sm,
  },
  saveButtonDisabled: {
    backgroundColor: COLORS.borderLight,
  },
  saveButtonText: {
    fontSize: 15,
    fontWeight: "700",
    color: COLORS.background,
  },
});
