import { useMemo, useState } from "react";
import { Alert, Pressable, StyleSheet, Text, TextInput, View } from "react-native";
import { CreditCard, Gift } from "lucide-react-native";
import { AppButton } from "../components/AppButton";
import { QrCodeCard } from "../components/QrCodeCard";
import { Screen } from "../components/Screen";
import { SectionHeader } from "../components/SectionHeader";
import { giftCards } from "../data/mockData";
import { colors } from "../theme/colors";
import { radius, spacing } from "../theme/spacing";
import { formatCurrency } from "../utils/format";

const presetAmounts = [10, 25, 50, 100];

export function GiftCardsScreen() {
  const [selectedAmount, setSelectedAmount] = useState<number | "custom">(25);
  const [customAmount, setCustomAmount] = useState("");
  const [recipient, setRecipient] = useState<"self" | "friend">("self");

  const currentAmount = useMemo(() => {
    if (selectedAmount !== "custom") {
      return selectedAmount;
    }

    return Number(customAmount.replace(",", ".")) || 0;
  }, [customAmount, selectedAmount]);

  return (
    <Screen>
      <View style={styles.header}>
        <Text style={styles.title}>Chèques cadeaux</Text>
        <Text style={styles.subtitle}>
          Achetez un montant à utiliser chez les commerçants partenaires Ambérieu Vitrines.
        </Text>
      </View>

      <View style={styles.card}>
        <View style={styles.cardHeader}>
          <Gift color={colors.primary} size={24} strokeWidth={2.6} />
          <Text style={styles.cardTitle}>Nouveau chèque cadeau</Text>
        </View>

        <View style={styles.amountGrid}>
          {presetAmounts.map((amount) => (
            <Pressable
              accessibilityRole="button"
              key={amount}
              onPress={() => setSelectedAmount(amount)}
              style={[styles.amountChip, selectedAmount === amount && styles.amountChipActive]}
            >
              <Text
                style={[
                  styles.amountText,
                  selectedAmount === amount && styles.amountTextActive
                ]}
              >
                {formatCurrency(amount)}
              </Text>
            </Pressable>
          ))}
          <Pressable
            accessibilityRole="button"
            onPress={() => setSelectedAmount("custom")}
            style={[styles.amountChip, selectedAmount === "custom" && styles.amountChipActive]}
          >
            <Text
              style={[
                styles.amountText,
                selectedAmount === "custom" && styles.amountTextActive
              ]}
            >
              Libre
            </Text>
          </Pressable>
        </View>

        {selectedAmount === "custom" ? (
          <TextInput
            value={customAmount}
            onChangeText={setCustomAmount}
            keyboardType="decimal-pad"
            placeholder="Montant libre"
            placeholderTextColor={colors.muted}
            style={styles.input}
          />
        ) : null}

        <View style={styles.segmented}>
          <Segment label="Pour moi" active={recipient === "self"} onPress={() => setRecipient("self")} />
          <Segment
            label="Pour un proche"
            active={recipient === "friend"}
            onPress={() => setRecipient("friend")}
          />
        </View>

        <AppButton
          label={`Payer ${formatCurrency(currentAmount)}`}
          icon={CreditCard}
          onPress={() => Alert.alert("Paiement", "Ouverture Stripe PaymentSheet pour le chèque cadeau.")}
        />
      </View>

      <QrCodeCard
        title="QR Code du dernier chèque"
        caption="Le commerçant scanne ce code au moment de l'encaissement."
        value={giftCards[0].id}
      />

      <View style={styles.section}>
        <SectionHeader title="Historique" subtitle={`${giftCards.length} chèques cadeaux`} />
        {giftCards.map((giftCard) => (
          <View key={giftCard.id} style={styles.historyRow}>
            <View>
              <Text style={styles.historyTitle}>{formatCurrency(giftCard.amount)}</Text>
              <Text style={styles.historyMeta}>
                {giftCard.recipient} · {giftCard.purchasedAt}
              </Text>
            </View>
            <Text
              style={[
                styles.status,
                giftCard.status === "active" ? styles.statusActive : styles.statusUsed
              ]}
            >
              {giftCard.status === "active" ? "Actif" : "Utilisé"}
            </Text>
          </View>
        ))}
      </View>
    </Screen>
  );
}

interface SegmentProps {
  label: string;
  active: boolean;
  onPress: () => void;
}

function Segment({ label, active, onPress }: SegmentProps) {
  return (
    <Pressable
      accessibilityRole="button"
      onPress={onPress}
      style={[styles.segment, active && styles.segmentActive]}
    >
      <Text style={[styles.segmentText, active && styles.segmentTextActive]}>{label}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  header: {
    gap: spacing.sm
  },
  title: {
    color: colors.ink,
    fontSize: 30,
    lineHeight: 34,
    fontWeight: "900"
  },
  subtitle: {
    color: colors.muted,
    fontSize: 14,
    lineHeight: 20,
    fontWeight: "600"
  },
  card: {
    borderRadius: radius.lg,
    borderWidth: 1,
    borderColor: colors.line,
    backgroundColor: colors.surface,
    padding: spacing.lg,
    gap: spacing.md
  },
  cardHeader: {
    flexDirection: "row",
    alignItems: "center",
    gap: spacing.sm
  },
  cardTitle: {
    color: colors.ink,
    fontSize: 18,
    fontWeight: "900"
  },
  amountGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: spacing.sm
  },
  amountChip: {
    minWidth: 86,
    minHeight: 42,
    borderRadius: radius.md,
    borderWidth: 1,
    borderColor: colors.line,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: colors.background,
    paddingHorizontal: spacing.md
  },
  amountChipActive: {
    backgroundColor: colors.primary,
    borderColor: colors.primary
  },
  amountText: {
    color: colors.ink,
    fontSize: 14,
    fontWeight: "900"
  },
  amountTextActive: {
    color: colors.surface
  },
  input: {
    minHeight: 48,
    borderRadius: radius.md,
    borderWidth: 1,
    borderColor: colors.line,
    paddingHorizontal: spacing.md,
    color: colors.ink,
    fontSize: 15,
    fontWeight: "800",
    backgroundColor: colors.background
  },
  segmented: {
    borderRadius: radius.md,
    backgroundColor: colors.background,
    padding: spacing.xs,
    flexDirection: "row",
    gap: spacing.xs
  },
  segment: {
    flex: 1,
    minHeight: 40,
    borderRadius: radius.sm,
    alignItems: "center",
    justifyContent: "center"
  },
  segmentActive: {
    backgroundColor: colors.surface
  },
  segmentText: {
    color: colors.muted,
    fontSize: 13,
    fontWeight: "900"
  },
  segmentTextActive: {
    color: colors.primary
  },
  section: {
    gap: spacing.md
  },
  historyRow: {
    borderRadius: radius.md,
    backgroundColor: colors.surface,
    borderWidth: 1,
    borderColor: colors.line,
    padding: spacing.md,
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between"
  },
  historyTitle: {
    color: colors.ink,
    fontSize: 16,
    fontWeight: "900"
  },
  historyMeta: {
    color: colors.muted,
    fontSize: 12,
    fontWeight: "700",
    marginTop: 3
  },
  status: {
    fontSize: 12,
    fontWeight: "900"
  },
  statusActive: {
    color: colors.success
  },
  statusUsed: {
    color: colors.muted
  }
});
