import { router, Stack, useLocalSearchParams } from "expo-router";
import { Alert, ScrollView, StyleSheet, Text, View } from "react-native";

import { AppBackground } from "@/components/AppBackground";
import { LoadingScreen } from "@/components/LoadingScreen";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { fonts, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import { useTabBarScrollPadding } from "@/lib/tab-bar-insets";
import type { ThemeColors } from "@/lib/theme-palette";
import { useThemedStyles } from "@/lib/use-themed-styles";
import { api } from "@/lib/trpc";

export default function BusinessDetailScreen() {
  const { colors } = useAppTheme();
  const styles = useThemedStyles(createBusinessDetailStyles);
  const { id } = useLocalSearchParams<{ id: string }>();
  const scrollPadding = useTabBarScrollPadding();
  const utils = api.useUtils();

  const businessQuery = api.businesses.getById.useQuery(
    { id: id ?? "" },
    { enabled: Boolean(id) },
  );

  const setDefault = api.businesses.setDefault.useMutation({
    onSuccess: () => {
      void utils.businesses.getAll.invalidate();
      if (id) void utils.businesses.getById.invalidate({ id });
      Alert.alert("Default updated", "This business is now your default.");
    },
    onError: (err) => Alert.alert("Could not set default", err.message),
  });

  if (!id) {
    return <LoadingScreen message="Invalid business" />;
  }

  if (businessQuery.isLoading) {
    return <LoadingScreen message="Loading business…" />;
  }

  const business = businessQuery.data;
  if (!business) {
    return <LoadingScreen message="Business not found" />;
  }

  return (
    <AppBackground>
      <Stack.Screen options={{ headerBackTitle: "Entities" }} />
      <ScrollView
        contentContainerStyle={[styles.container, { paddingBottom: scrollPadding }]}
        contentInsetAdjustmentBehavior="automatic"
        scrollIndicatorInsets={{ bottom: scrollPadding }}
      >
        <View style={styles.hero}>
          <View style={styles.nameRow}>
            <Text style={styles.name}>{business.name}</Text>
            {business.isDefault ? <Text style={styles.badge}>Default</Text> : null}
          </View>
          {business.nickname ? <Text style={styles.meta}>{business.nickname}</Text> : null}
          {business.email ? <Text style={styles.meta}>{business.email}</Text> : null}
          {business.phone ? <Text style={styles.meta}>{business.phone}</Text> : null}
          {business.website ? <Text style={styles.meta}>{business.website}</Text> : null}
        </View>

        <Card title="Details">
          {business.taxId ? (
            <DetailRow label="Tax ID" value={business.taxId} />
          ) : null}
          <DetailRow
            label="Email sending"
            value={business.resendDomain ? "Configured" : "Not configured"}
          />
        </Card>

        {(business.addressLine1 || business.city || business.state) && (
          <Card title="Address">
            {business.addressLine1 ? (
              <Text style={styles.body}>{business.addressLine1}</Text>
            ) : null}
            {business.addressLine2 ? (
              <Text style={styles.body}>{business.addressLine2}</Text>
            ) : null}
            {(business.city || business.state || business.postalCode) && (
              <Text style={styles.body}>
                {[business.city, business.state, business.postalCode].filter(Boolean).join(", ")}
              </Text>
            )}
            {business.country ? <Text style={styles.body}>{business.country}</Text> : null}
          </Card>
        )}

        <View style={styles.actions}>
          <Button
            title="Edit business"
            onPress={() => router.push(`/(app)/entities/businesses/edit/${business.id}`)}
          />
          {!business.isDefault ? (
            <Button
              title="Set as default"
              variant="secondary"
              loading={setDefault.isPending}
              onPress={() => setDefault.mutate({ id: business.id })}
            />
          ) : null}
        </View>
      </ScrollView>
    </AppBackground>
  );
}

function DetailRow({ label, value }: { label: string; value: string }) {
  const { colors } = useAppTheme();
  return (
    <View style={detailStyles.row}>
      <Text style={[detailStyles.label, { color: colors.mutedForeground }]}>{label}</Text>
      <Text style={[detailStyles.value, { color: colors.foreground }]}>{value}</Text>
    </View>
  );
}

const detailStyles = StyleSheet.create({
  row: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    paddingVertical: 4,
  },
  label: {
    fontFamily: fonts.body,
    fontSize: 14,
  },
  value: {
    fontFamily: fonts.bodySemiBold,
    fontSize: 14,
  },
});

const createBusinessDetailStyles = (colors: ThemeColors, isDark: boolean) =>
  StyleSheet.create({
    container: {
      padding: spacing.md,
      gap: spacing.md,
    },
    hero: {
      gap: 4,
    },
    nameRow: {
      flexDirection: "row",
      alignItems: "center",
      gap: spacing.sm,
      flexWrap: "wrap",
    },
    name: {
      fontSize: 24,
      lineHeight: 28,
      fontFamily: fonts.heading,
      color: colors.foreground,
    },
    badge: {
      fontSize: 11,
      fontFamily: fonts.bodySemiBold,
      color: colors.primary,
      backgroundColor: isDark ? "rgba(74, 222, 128, 0.15)" : colors.muted,
      paddingHorizontal: spacing.sm,
      paddingVertical: 2,
      borderRadius: 999,
      overflow: "hidden",
    },
    meta: {
      fontSize: 14,
      fontFamily: fonts.body,
      color: colors.mutedForeground,
    },
    body: {
      fontFamily: fonts.body,
      fontSize: 14,
      color: colors.foreground,
      lineHeight: 20,
    },
    actions: {
      gap: spacing.sm,
    },
  });
