import { RefreshControl, StyleSheet, Text, View } from "react-native";

import { AppBackground } from "@/components/AppBackground";
import { LoadingScreen } from "@/components/LoadingScreen";
import { PageHeader } from "@/components/PageHeader";
import { SwipeableRow } from "@/components/SwipeableRow";
import { TabPage } from "@/components/TabPage";
import { TabScrollView } from "@/components/TabScrollView";
import { fonts, spacing } from "@/constants/theme";
import { useAppTheme } from "@/contexts/ThemeContext";
import { formatCurrency, formatDate } from "@/lib/format";
import { api } from "@/lib/trpc";

export default function RecurringScreen() {
  const { colors } = useAppTheme();
  const utils = api.useUtils();
  const query = api.recurringInvoices.getAll.useQuery();

  const pause = api.recurringInvoices.pause.useMutation({
    onSuccess: () => void query.refetch(),
  });
  const resume = api.recurringInvoices.resume.useMutation({
    onSuccess: () => void query.refetch(),
  });
  const generateNow = api.recurringInvoices.generateNow.useMutation({
    onSuccess: () => {
      void utils.invoices.getAll.invalidate();
      void query.refetch();
    },
  });

  if (query.isLoading) {
    return <LoadingScreen message="Loading recurring invoices…" />;
  }

  const items = query.data ?? [];

  return (
    <AppBackground>
      <TabPage>
        <TabScrollView
          header={
            <PageHeader
              title="Recurring"
              subtitle={`${items.length} schedule${items.length === 1 ? "" : "s"}`}
            />
          }
          refreshControl={
            <RefreshControl
              refreshing={query.isRefetching}
              onRefresh={() => void query.refetch()}
              tintColor={colors.primary}
            />
          }
        >
          {items.length === 0 ? (
            <Text style={{ color: colors.mutedForeground, fontFamily: fonts.body }}>
              No recurring invoices yet. Create them on the web dashboard for now.
            </Text>
          ) : (
            items.map((item) => (
              <SwipeableRow
                key={item.id}
                actions={[
                  {
                    key: "generate",
                    label: "Run",
                    icon: "play-outline",
                    color: "#fff",
                    backgroundColor: colors.primary,
                    onPress: () => generateNow.mutate({ id: item.id }),
                  },
                  {
                    key: "toggle",
                    label: item.status === "active" ? "Pause" : "Resume",
                    icon: item.status === "active" ? "pause-outline" : "play-outline",
                    color: "#fff",
                    backgroundColor: colors.mutedForeground,
                    onPress: () =>
                      item.status === "active"
                        ? pause.mutate({ id: item.id })
                        : resume.mutate({ id: item.id }),
                  },
                ]}
              >
                <View style={styles.row}>
                  <View style={{ flex: 1, gap: 2 }}>
                    <Text style={[styles.title, { color: colors.foreground }]}>{item.name}</Text>
                    <Text style={{ color: colors.mutedForeground, fontFamily: fonts.body }}>
                      {item.client?.name ?? "Client"} · {item.schedule} · {item.status}
                    </Text>
                    <Text style={{ color: colors.mutedForeground, fontFamily: fonts.body }}>
                      Next due {formatDate(item.nextDueAt)}
                    </Text>
                  </View>
                  <Text style={[styles.title, { color: colors.foreground }]}>
                    {formatCurrency(
                      item.items.reduce((sum, line) => sum + line.hours * line.rate, 0),
                      item.currency,
                    )}
                  </Text>
                </View>
              </SwipeableRow>
            ))
          )}
        </TabScrollView>
      </TabPage>
    </AppBackground>
  );
}

const styles = StyleSheet.create({
  row: {
    flexDirection: "row",
    gap: spacing.md,
    paddingVertical: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: "rgba(0,0,0,0.08)",
  },
  title: {
    fontFamily: fonts.bodySemiBold,
    fontSize: 15,
  },
});
