import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  TouchableOpacity,
  Image,
  ActivityIndicator,
  Alert,
  TextInput,
  Platform,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useRouter, Stack } from "expo-router";
import {
  ChevronLeft,
  Repeat,
  Plus,
  Calendar,
  DollarSign,
  Trash2,
  X,
} from "lucide-react-native";

import Colors from "@/constants/colors";
import { trpc } from "@/lib/trpc";
import { useAuth } from "@/lib/auth-context";

type Frequency = "daily" | "weekly" | "biweekly" | "monthly" | "yearly";

const frequencyLabels: Record<Frequency, string> = {
  daily: "Daily",
  weekly: "Weekly",
  biweekly: "Bi-weekly",
  monthly: "Monthly",
  yearly: "Yearly",
};

export default function RecurringPaymentsScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { user } = useAuth();
  const [showCreate, setShowCreate] = useState(false);

  const recurringPaymentsQuery = trpc.recurring.list.useQuery();
  const cancelMutation = trpc.recurring.cancel.useMutation({
    onSuccess: () => {
      recurringPaymentsQuery.refetch();
      Alert.alert("Success", "Recurring payment cancelled");
    },
  });

  const payments = recurringPaymentsQuery.data || [];

  const handleCancel = (paymentId: string) => {
    Alert.alert(
      "Cancel Recurring Payment",
      "Are you sure you want to cancel this recurring payment?",
      [
        { text: "No", style: "cancel" },
        {
          text: "Yes, Cancel",
          style: "destructive",
          onPress: () => cancelMutation.mutate({ paymentId }),
        },
      ]
    );
  };

  const formatNextPayment = (date: Date) => {
    const now = new Date();
    const diff = date.getTime() - now.getTime();
    const days = Math.ceil(diff / (1000 * 60 * 60 * 24));

    if (days === 0) return "Today";
    if (days === 1) return "Tomorrow";
    if (days < 7) return `In ${days} days`;
    return date.toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
    });
  };

  if (showCreate) {
    return (
      <CreateRecurringPayment
        onClose={() => setShowCreate(false)}
        onSuccess={() => {
          setShowCreate(false);
          recurringPaymentsQuery.refetch();
        }}
      />
    );
  }

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ headerShown: false }} />

      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => router.back()}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <ChevronLeft color={Colors.dark.text} size={24} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>Recurring Payments</Text>
        <TouchableOpacity
          onPress={() => setShowCreate(true)}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <Plus color={Colors.dark.primary} size={24} />
        </TouchableOpacity>
      </View>

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={scrollViewWebProps.showsVerticalScrollIndicator}
      >
        {recurringPaymentsQuery.isLoading ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={Colors.dark.primary} />
            <Text style={styles.loadingText}>Loading recurring payments...</Text>
          </View>
        ) : payments.length > 0 ? (
          payments.map((payment) => {
            const isOutgoing = payment.from?.id === user?.id;
            const otherUser = isOutgoing ? payment.to : payment.from;

            return (
              <View key={payment.id} style={styles.paymentCard}>
                <View style={styles.paymentHeader}>
                  <Image
                    source={{
                      uri:
                        otherUser?.avatar ||
                        `https://i.pravatar.cc/150?u=${otherUser?.id}`,
                    }}
                    style={styles.avatar}
                  />
                  <View style={styles.paymentInfo}>
                    <Text style={styles.paymentName}>
                      {isOutgoing ? "To" : "From"} {otherUser?.displayName}
                    </Text>
                    <Text style={styles.paymentUsername}>
                      @{otherUser?.username}
                    </Text>
                  </View>
                  <View style={styles.statusBadge}>
                    <View
                      style={[
                        styles.statusDot,
                        { backgroundColor: payment.isActive ? Colors.dark.success : Colors.dark.textTertiary },
                      ]}
                    />
                  </View>
                </View>

                <View style={styles.paymentDetails}>
                  <View style={styles.detailRow}>
                    <View style={styles.detailItem}>
                      <DollarSign color={Colors.dark.primary} size={18} />
                      <Text style={styles.detailLabel}>Amount</Text>
                    </View>
                    <Text style={styles.detailValue}>
                      ${payment.amount.toFixed(2)}
                    </Text>
                  </View>

                  <View style={styles.detailRow}>
                    <View style={styles.detailItem}>
                      <Repeat color={Colors.dark.secondary} size={18} />
                      <Text style={styles.detailLabel}>Frequency</Text>
                    </View>
                    <Text style={styles.detailValue}>
                      {frequencyLabels[payment.frequency as Frequency]}
                    </Text>
                  </View>

                  <View style={styles.detailRow}>
                    <View style={styles.detailItem}>
                      <Calendar color={Colors.dark.warning} size={18} />
                      <Text style={styles.detailLabel}>Next Payment</Text>
                    </View>
                    <Text style={styles.detailValue}>
                      {formatNextPayment(payment.nextPaymentDate)}
                    </Text>
                  </View>

                  {payment.note && (
                    <View style={styles.noteContainer}>
                      <Text style={styles.noteLabel}>Note</Text>
                      <Text style={styles.noteText}>{payment.note}</Text>
                    </View>
                  )}
                </View>

                {isOutgoing && (
                  <View style={styles.paymentActions}>
                    <TouchableOpacity
                      style={styles.actionButton}
                      onPress={() => handleCancel(payment.id)}
                      disabled={!payment.isActive || cancelMutation.isPending}
                    >
                      <Trash2 color={Colors.dark.error} size={18} />
                      <Text style={styles.actionButtonText}>Cancel</Text>
                    </TouchableOpacity>
                  </View>
                )}
              </View>
            );
          })
        ) : (
          <View style={styles.emptyContainer}>
            <Repeat color={Colors.dark.textTertiary} size={64} />
            <Text style={styles.emptyTitle}>No Recurring Payments</Text>
            <Text style={styles.emptyText}>
              Set up automatic payments to people you pay regularly
            </Text>
            <TouchableOpacity
              style={styles.createButton}
              onPress={() => setShowCreate(true)}
            >
              <Text style={styles.createButtonText}>Create Recurring Payment</Text>
            </TouchableOpacity>
          </View>
        )}
      </ScrollView>
    </View>
  );
}

function CreateRecurringPayment({
  onClose,
  onSuccess,
}: {
  onClose: () => void;
  onSuccess: () => void;
}) {
  const [username, setUsername] = useState("");
  const [amount, setAmount] = useState("");
  const [frequency, setFrequency] = useState<Frequency>("monthly");
  const [note, setNote] = useState("");
  const [showUserPicker, setShowUserPicker] = useState(false);
  const [selectedUser, setSelectedUser] = useState<{
    id: string;
    username: string;
    displayName: string;
    avatar?: string;
  } | null>(null);

  const searchQuery = trpc.users.search.useQuery(
    { query: username },
    { enabled: username.length > 0 && showUserPicker }
  );

  const createMutation = trpc.recurring.create.useMutation({
    onSuccess: () => {
      onSuccess();
    },
    onError: (error) => {
      Alert.alert("Error", "Failed to create recurring payment.");
    },
  });
  const parsedAmount = Number.parseFloat(amount);
  const hasValidAmount = Number.isFinite(parsedAmount) && parsedAmount > 0;

  const handleCreate = () => {
    if (!selectedUser) {
      Alert.alert("Error", "Please select a recipient");
      return;
    }
    if (!hasValidAmount) {
      Alert.alert("Error", "Please enter a valid amount");
      return;
    }

    createMutation.mutate({
      toUsername: selectedUser.username,
      amount: parsedAmount,
      frequency,
      note: note || undefined,
    });
  };

  const insets = useSafeAreaInsets();

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={onClose}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <X color={Colors.dark.text} size={24} />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>New Recurring Payment</Text>
        <View style={{ width: 24 }} />
      </View>

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.createContent}
        keyboardShouldPersistTaps="handled"
      >
        <View style={styles.section}>
          <Text style={styles.sectionLabel}>Recipient</Text>
          {selectedUser ? (
            <View style={styles.selectedUserCard}>
              <Image
                source={{
                  uri: selectedUser.avatar || `https://i.pravatar.cc/150?u=${selectedUser.id}`,
                }}
                style={styles.selectedAvatar}
              />
              <View style={styles.selectedUserInfo}>
                <Text style={styles.selectedUserName}>{selectedUser.displayName}</Text>
                <Text style={styles.selectedUserUsername}>@{selectedUser.username}</Text>
              </View>
              <TouchableOpacity onPress={() => setSelectedUser(null)}>
                <X color={Colors.dark.error} size={20} />
              </TouchableOpacity>
            </View>
          ) : (
            <>
              <TextInput
                style={styles.input}
                value={username}
                onChangeText={(text) => {
                  setUsername(text);
                  setShowUserPicker(true);
                }}
                placeholder="Search for a user..."
                placeholderTextColor={Colors.dark.textTertiary}
              />
              {showUserPicker && searchQuery.data && searchQuery.data.length > 0 && (
                <View style={styles.userResults}>
                  {searchQuery.data.map((user) => (
                    <TouchableOpacity
                      key={user.id}
                      style={styles.userResultCard}
                      onPress={() => {
                        setSelectedUser(user);
                        setShowUserPicker(false);
                        setUsername("");
                      }}
                    >
                      <Image
                        source={{
                          uri: user.avatar || `https://i.pravatar.cc/150?u=${user.id}`,
                        }}
                        style={styles.userResultAvatar}
                      />
                      <View>
                        <Text style={styles.userResultName}>{user.displayName}</Text>
                        <Text style={styles.userResultUsername}>@{user.username}</Text>
                      </View>
                    </TouchableOpacity>
                  ))}
                </View>
              )}
            </>
          )}
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionLabel}>Amount</Text>
          <View style={styles.amountInputContainer}>
            <Text style={styles.currencySymbol}>$</Text>
            <TextInput
              style={styles.amountInput}
              value={amount}
              onChangeText={setAmount}
              keyboardType="decimal-pad"
              placeholder="0.00"
              placeholderTextColor={Colors.dark.textTertiary}
            />
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionLabel}>Frequency</Text>
          <View style={styles.frequencyGrid}>
            {(Object.keys(frequencyLabels) as Frequency[]).map((freq) => (
              <TouchableOpacity
                key={freq}
                style={[
                  styles.frequencyButton,
                  frequency === freq && styles.frequencyButtonActive,
                ]}
                onPress={() => setFrequency(freq)}
              >
                <Text
                  style={[
                    styles.frequencyButtonText,
                    frequency === freq && styles.frequencyButtonTextActive,
                  ]}
                >
                  {frequencyLabels[freq]}
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionLabel}>Note (Optional)</Text>
          <TextInput
            style={styles.noteInput}
            value={note}
            onChangeText={setNote}
            placeholder="What's this for?"
            placeholderTextColor={Colors.dark.textTertiary}
            multiline
            maxLength={200}
          />
        </View>

        <View style={styles.infoBox}>
          <Text style={styles.infoText}>
            The first payment will be processed {frequency === "daily" ? "tomorrow" : `next ${frequency.replace("biweekly", "two weeks")}`}.
            You can cancel this at any time.
          </Text>
        </View>
      </ScrollView>

      <View style={[styles.footer, { paddingBottom: insets.bottom + 20 }]}>
        <TouchableOpacity
          style={[
            styles.submitButton,
            (!selectedUser || !amount || createMutation.isPending) &&
              styles.submitButtonDisabled,
          ]}
          onPress={handleCreate}
          disabled={!selectedUser || !amount || createMutation.isPending}
        >
          {createMutation.isPending ? (
            <ActivityIndicator color={Colors.dark.background} />
          ) : (
            <Text style={styles.submitButtonText}>Create Recurring Payment</Text>
          )}
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    paddingHorizontal: 20,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: Colors.dark.border,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 20,
    gap: 16,
  },
  createContent: {
    padding: 20,
    gap: 24,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 60,
    gap: 16,
  },
  loadingText: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    paddingVertical: 80,
    gap: 16,
  },
  emptyTitle: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginTop: 16,
  },
  emptyText: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center",
    paddingHorizontal: 40,
    lineHeight: 20,
  },
  createButton: {
    backgroundColor: Colors.dark.primary,
    paddingHorizontal: 24,
    paddingVertical: 12,
    borderRadius: 12,
    marginTop: 16,
  },
  createButtonText: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.background,
  },
  paymentCard: {
    backgroundColor: Colors.dark.surface,
    borderRadius: 16,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 16,
  },
  paymentHeader: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 16,
    gap: 12,
  },
  avatar: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: Colors.dark.surfaceElevated,
  },
  paymentInfo: {
    flex: 1,
  },
  paymentName: {
    fontSize: 16,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  paymentUsername: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  statusBadge: {
    padding: 8,
  },
  statusDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
  },
  paymentDetails: {
    gap: 12,
  },
  detailRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  detailItem: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  detailLabel: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
  },
  detailValue: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  noteContainer: {
    marginTop: 8,
    paddingTop: 12,
    borderTopWidth: 1,
    borderTopColor: Colors.dark.border,
  },
  noteLabel: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginBottom: 4,
  },
  noteText: {
    fontSize: 14,
    color: Colors.dark.text,
    lineHeight: 20,
  },
  paymentActions: {
    flexDirection: "row",
    marginTop: 16,
    paddingTop: 16,
    borderTopWidth: 1,
    borderTopColor: Colors.dark.border,
    gap: 12,
  },
  actionButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: Colors.dark.surfaceElevated,
    paddingVertical: 10,
    paddingHorizontal: 16,
    borderRadius: 8,
    gap: 6,
  },
  actionButtonText: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.error,
  },
  section: {
    gap: 12,
  },
  sectionLabel: {
    fontSize: 13,
    fontWeight: "700" as const,
    color: Colors.dark.textSecondary,
    textTransform: "uppercase",
    letterSpacing: 0.5,
  },
  input: {
    backgroundColor: Colors.dark.surface,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    borderRadius: 12,
    paddingHorizontal: 16,
    paddingVertical: 14,
    fontSize: 16,
    color: Colors.dark.text,
    ...Platform.select({
      web: {
        outlineStyle: "none" as const,
      },
    }),
  },
  selectedUserCard: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: Colors.dark.surface,
    borderWidth: 1,
    borderColor: Colors.dark.primary,
    borderRadius: 12,
    padding: 12,
    gap: 12,
  },
  selectedAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: Colors.dark.surfaceElevated,
  },
  selectedUserInfo: {
    flex: 1,
  },
  selectedUserName: {
    fontSize: 15,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  selectedUserUsername: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  userResults: {
    backgroundColor: Colors.dark.surface,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    borderRadius: 12,
    overflow: "hidden",
    maxHeight: 200,
  },
  userResultCard: {
    flexDirection: "row",
    alignItems: "center",
    padding: 12,
    gap: 12,
    borderBottomWidth: 1,
    borderBottomColor: Colors.dark.border,
  },
  userResultAvatar: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: Colors.dark.surfaceElevated,
  },
  userResultName: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.text,
  },
  userResultUsername: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginTop: 2,
  },
  amountInputContainer: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: Colors.dark.surface,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    borderRadius: 12,
    paddingHorizontal: 16,
    paddingVertical: 12,
    gap: 8,
  },
  currencySymbol: {
    fontSize: 28,
    fontWeight: "700" as const,
    color: Colors.dark.primary,
  },
  amountInput: {
    flex: 1,
    fontSize: 28,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    ...Platform.select({
      web: {
        outlineStyle: "none" as const,
      },
    }),
  },
  frequencyGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 12,
  },
  frequencyButton: {
    backgroundColor: Colors.dark.surface,
    borderWidth: 2,
    borderColor: Colors.dark.border,
    borderRadius: 12,
    paddingVertical: 12,
    paddingHorizontal: 20,
  },
  frequencyButtonActive: {
    backgroundColor: `${Colors.dark.primary}20`,
    borderColor: Colors.dark.primary,
  },
  frequencyButtonText: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  frequencyButtonTextActive: {
    color: Colors.dark.primary,
  },
  noteInput: {
    backgroundColor: Colors.dark.surface,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    borderRadius: 12,
    paddingHorizontal: 16,
    paddingVertical: 14,
    fontSize: 16,
    color: Colors.dark.text,
    minHeight: 80,
    textAlignVertical: "top",
    ...Platform.select({
      web: {
        outlineStyle: "none" as const,
      },
    }),
  },
  infoBox: {
    backgroundColor: `${Colors.dark.primary}10`,
    padding: 16,
    borderRadius: 12,
  },
  infoText: {
    fontSize: 13,
    color: Colors.dark.textSecondary,
    lineHeight: 18,
  },
  footer: {
    paddingHorizontal: 20,
    paddingTop: 16,
    borderTopWidth: 1,
    borderTopColor: Colors.dark.border,
  },
  submitButton: {
    backgroundColor: Colors.dark.primary,
    paddingVertical: 18,
    borderRadius: 16,
    alignItems: "center",
  },
  submitButtonDisabled: {
    opacity: 0.5,
  },
  submitButtonText: {
    fontSize: 18,
    fontWeight: "700" as const,
    color: Colors.dark.background,
  },
});
