import React from "react";
import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
import { useRouter } from "expo-router";
import { useSelector } from "react-redux";
import { RootState } from "@/store/rootReducer";
import Header from "@/components/common/Header";
import CheckCircle from "@/assets/icons/check_circle.svg";
import Pending from "@/assets/icons/pending.svg";
import Failed from "@/assets/icons/cancel.svg";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useTranslation } from "react-i18next";

const PaymentConfirmationScreen = () => {
  const router = useRouter();
  const { paymentOrder, due_amount } = useSelector(
    (state: RootState) => state.payments
  );

  const insets = useSafeAreaInsets();

  // Get payment status - assuming it comes from paymentOrder.status
  const paymentStatus = paymentOrder?.status || "confirmed";

  // Format amount with currency
  const formatAmount = (amount: number | null) => {
    if (!amount) return "₹0";
    return `₹${amount.toLocaleString("en-IN")}`;
  };

  // Format date
  const formatDate = (dateString?: string) => {
    if (!dateString)
      return new Date().toLocaleString("en-IN", {
        day: "numeric",
        month: "long",
        year: "numeric",
        hour: "numeric",
        minute: "2-digit",
        hour12: true,
        weekday: "long",
      });

    return new Date(dateString).toLocaleString("en-IN", {
      day: "numeric",
      month: "long",
      year: "numeric",
      hour: "numeric",
      minute: "2-digit",
      hour12: true,
      weekday: "long",
    });
  };

  // Get icon and text based on status
  const getStatusDisplay = () => {
    switch (paymentStatus) {
      case "confirmed":
        return {
          icon: <CheckCircle />,
          text: "Payment successful",
          iconContainerStyle: styles.successIconContainer,
        };
      case "failure":
        return {
          icon: <Failed />,
          text: "Payment failed",
          iconContainerStyle: styles.failureIconContainer,
        };
      case "pending":
        return {
          icon: <Pending />,
          text: "Payment pending",
          iconContainerStyle: styles.pendingIconContainer,
        };
      default:
        return {
          icon: <CheckCircle />,
          text: "Payment successful",
          iconContainerStyle: styles.successIconContainer,
        };
    }
  };

  const statusDisplay = getStatusDisplay();

  // Helper function to display value or "--" if missing
  const displayValue = (value: any) => {
    return value ? String(value) : "--";
  };
  const { t } = useTranslation();
  return (
    <View style={styles.container}>
      <Header title={`${t("payment.payment-status")}`} />

      <View style={styles.contentFrame}>
        <View style={styles.qrFrame}>
          <View style={styles.paymentStatusContainer}>
            <View style={statusDisplay.iconContainerStyle}>
              {statusDisplay.icon}
            </View>
            <Text style={styles.amountText}>
              {formatAmount(paymentOrder?.amount || due_amount)}
            </Text>

            <View style={styles.statusContainer}>
              <Text style={styles.statusText}>{statusDisplay.text}</Text>
              <Text style={styles.dateText}>
                {formatDate(paymentOrder?.transaction_date)}
              </Text>
            </View>
          </View>

          <View style={styles.divider} />

          <View style={styles.transactionContainer}>
            <Text style={styles.sectionHeader}>{`${t(
              "payment.transaction-details"
            )}`}</Text>

            <View style={styles.detailRow}>
              <Text style={styles.detailLabel}>{`${t(
                "payment.payment-mode"
              )}`}</Text>
              <Text style={styles.detailValue}>
                {displayValue(paymentOrder?.payment_mode?.[0])}
              </Text>
            </View>
            <View style={styles.detailRow}>
              <Text style={styles.detailLabel}>{`${t(
                "payment.paid-to"
              )}`}</Text>
              <Text style={styles.detailValue}>
                {displayValue(paymentOrder?.upi_handle)}
              </Text>
            </View>

            <View style={styles.detailRow}>
              <Text style={styles.detailLabel}>{`${t(
                "payment.paid-by"
              )}`}</Text>
              <Text style={styles.detailValue}>
                {displayValue(paymentOrder?.paid_by_upi_handle)}
              </Text>
            </View>

            <View style={styles.detailRow}>
              <Text style={styles.detailLabel}>{`${t(
                "payment.order-id"
              )}`}</Text>
              <Text style={styles.detailValue}>
                {displayValue(paymentOrder?.order_id)}
              </Text>
            </View>

            <View style={styles.detailRow}>
              <Text style={styles.detailLabel}>{`${t(
                "payment.transaction-id"
              )}`}</Text>
              <Text style={styles.detailValue}>
                {displayValue(
                  paymentOrder?.transaction_id ||
                    paymentOrder?.transaction_order_id
                )}
              </Text>
            </View>
            <View style={styles.detailRow}>
              <Text style={styles.detailLabel}>RRN</Text>
              <Text style={styles.detailValue}>
                {displayValue(paymentOrder?.payment_reference_id)}
              </Text>
            </View>
          </View>
        </View>
        <TouchableOpacity
          style={[styles.primaryButton, { marginBottom: insets.bottom }]}
          onPress={() => router.replace("/(tabs)/payments")}
        >
          <Text style={styles.buttonText}>OK</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

export default PaymentConfirmationScreen;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#f3f4f6", // Light gray background
  },
  contentFrame: {
    flex: 1,
    paddingHorizontal: 16,
    paddingBottom: 16,
    justifyContent: "space-between",
    marginTop: 8,
  },
  qrFrame: {
    backgroundColor: "#fcfcfc",
    borderRadius: 8,
    padding: 16,
    paddingVertical: 32,
  },
  paymentStatusContainer: {
    alignItems: "center",
  },
  successIconContainer: {
    marginBottom: 16,
    alignItems: "center",
  },
  failureIconContainer: {
    marginBottom: 16,
    alignItems: "center",
  },
  pendingIconContainer: {
    marginBottom: 16,
    alignItems: "center",
  },
  successIcon: {
    // Icon styling handled by Ionicons
  },
  amountText: {
    fontSize: 20,
    fontWeight: "600",
    color: "#252a34",
    textAlign: "center",
    marginBottom: 16,
  },
  statusContainer: {
    alignItems: "center",
    gap: 4,
  },
  statusText: {
    fontSize: 14,
    color: "#252a34",
    textAlign: "center",
  },
  dateText: {
    fontSize: 14,
    color: "#252a34",
    textAlign: "center",
  },
  divider: {
    height: 1,
    backgroundColor: "#e5e9f0",
    marginVertical: 24,
  },
  transactionContainer: {
    gap: 8,
  },
  sectionHeader: {
    fontSize: 14,
    fontWeight: "600",
    color: "#252a34",
  },
  detailRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
    paddingVertical: 2,
  },
  detailLabel: {
    fontSize: 14,
    color: "#252a34",
    flex: 1,
  },
  detailValue: {
    fontSize: 14,
    fontWeight: "600",
    color: "#252a34",
    textAlign: "left",
    flex: 1,
  },
  primaryButton: {
    backgroundColor: "#008761",
    height: 40,
    borderRadius: 4,
    justifyContent: "center",
    alignItems: "center",
  },
  buttonText: {
    color: "#fcfcfc",
    fontSize: 14,
    fontWeight: "500",
  },
});
