import Header from "@/components/common/Header";
import ProgressCard from "@/components/common/ProgressCard";
import { RootState } from "@/store/rootReducer";
import React from "react";
import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
import { useSelector } from "react-redux";

interface MyPlan {
  planType?: string;
  totalCost?: number;
  downPayment?: number;
  totalEmi?: number;
  monthlyEmi?: number;
  installmentsPaid?: number;
  totalInstallments?: number;
  emiPaidTillNow?: number;
  totalAmountDue?: number;
}

const MyPlanScreen: React.FC = () => {
  const myPlan = useSelector((state: RootState) => state.payments.myPlan);
  const dueAmount = useSelector(
    (state: RootState) => state.payments.due_amount
  );

  // Helper function to format currency
  const formatCurrency = (amount?: number | null): string => {
    if (amount == null) return "---";
    return `₹${amount.toLocaleString("en-IN")}`;
  };

  // Helper function to display value or fallback
  const displayValue = (value?: string | number | null): string => {
    if (value == null || value === "") return "---";
    return value.toString();
  };

  // Calculate progress percentage for EMI progress bar
  const getProgressPercentage = (
    firstValue: number,
    secondValue: number
  ): number => {
    if (!firstValue || !secondValue) return 0;
    return (firstValue / secondValue) * 100;
  };

  return (
    <View style={styles.container}>
      <Header title="My Plan" showBackButton={true} />

      <View style={styles.contentFrame}>
        {/* Plan Details Card */}
        <View style={styles.card}>
          <Text style={styles.cardTitle}>Plan Details</Text>
          <View style={styles.divider} />

          <View style={styles.content}>
            {/* Plan Type Row */}
            <View style={styles.row}>
              <Text style={styles.label}>Plan Type</Text>
              <Text style={styles.value}>
                {displayValue(myPlan?.no_of_emi)}
              </Text>
            </View>

            {/* Total Cost Row */}
            <View style={styles.row}>
              <Text style={styles.label}>Total Cost</Text>
              <Text style={styles.value}>
                {formatCurrency(myPlan?.total_amount)}
              </Text>
            </View>

            {/* Down Payment Row */}
            <View style={styles.row}>
              <Text style={styles.label}>Down Payment</Text>
              <Text style={styles.value}>
                {formatCurrency(myPlan?.down_payment)}
              </Text>
            </View>

            {/* Total EMI Row */}
            <View style={styles.row}>
              <Text style={styles.label}>Total EMI</Text>
              <Text style={styles.value}>
                {formatCurrency(myPlan?.total_emi)}
              </Text>
            </View>
          </View>
        </View>

        {/* Total Amount Due Card */}
        <View style={styles.card}>
          <Text style={styles.centerLabel}>Total Amount Due</Text>
          <View style={styles.amountContainer}>
            <Text style={styles.dueAmount}>{formatCurrency(dueAmount)}</Text>
          </View>
        </View>

        <View style={styles.twoColumnContainer}>
          {/* Monthly EMI Card */}
          <View style={styles.halfCard}>
            <Text style={styles.label}>Monthly EMI</Text>
            <Text style={styles.value}>
              {formatCurrency(myPlan?.total_emi)}
            </Text>
          </View>

          <View style={styles.halfCard}>
            <Text style={styles.label}>Installments Paid</Text>
            <View style={styles.installmentRow}>
              <Text style={styles.value}>
                {displayValue(myPlan?.installment_paid)}
              </Text>
              <Text style={styles.installmentTotal}>
                / {displayValue(myPlan?.no_of_emi)}
              </Text>
            </View>
          </View>
        </View>

        <ProgressCard
          title="EMI Paid Till Now"
          firstText={formatCurrency(myPlan?.current_amount)}
          secondText={formatCurrency(myPlan?.total_emi)}
          percentage={getProgressPercentage(
            myPlan?.current_amount || 0,
            myPlan?.total_emi || 0
          )}
        />

        <TouchableOpacity style={styles.payButton}>
          <Text style={styles.payButtonText}>Pay EMI</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F3F5F8",
    paddingTop: 16,
  },
  header: {
    paddingHorizontal: 16,
    paddingVertical: 16,
    backgroundColor: "#F3F5F8",
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: "600",
    color: "#252A34",
  },
  contentFrame: {
    flex: 1,
    paddingHorizontal: 16,
    paddingBottom: 16,
    gap: 16,
  },
  card: {
    backgroundColor: "#FCFCFC",
    borderRadius: 8,
    padding: 12,
    gap: 12,
  },
  cardTitle: {
    fontSize: 14,
    fontWeight: "600",
    color: "#252A34",
    height: 20,
  },
  divider: {
    height: 1,
    backgroundColor: "#E5E9F0",
  },
  content: {
    gap: 8,
  },
  row: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    height: 20,
  },
  label: {
    fontSize: 14,
    fontWeight: "400",
    color: "#252A34",
  },
  value: {
    fontSize: 14,
    fontWeight: "600",
    color: "#252A34",
  },
  centerLabel: {
    fontSize: 14,
    fontWeight: "400",
    color: "#252A34",
    textAlign: "center",
    height: 20,
  },
  amountContainer: {
    height: 28,
    justifyContent: "center",
    alignItems: "center",
  },
  dueAmount: {
    fontSize: 20,
    fontWeight: "600",
    color: "#252A34",
    textAlign: "center",
  },
  twoColumnContainer: {
    flexDirection: "row",
    gap: 16,
  },
  halfCard: {
    flex: 1,
    backgroundColor: "#FCFCFC",
    borderRadius: 8,
    padding: 12,
    gap: 8,
    height: 72,
  },
  installmentRow: {
    flexDirection: "row",
    alignItems: "flex-end",
    gap: 4,
  },
  installmentTotal: {
    fontSize: 14,
    fontWeight: "500",
    color: "#565F70",
  },
  progressAmountRow: {
    flexDirection: "row",
    alignItems: "flex-end",
    gap: 4,
  },
  progressTotal: {
    fontSize: 14,
    fontWeight: "500",
    color: "#565F70",
  },
  progressBarContainer: {
    width: "100%",
    height: 8,
  },
  progressBarBackground: {
    width: "100%",
    height: 8,
    backgroundColor: "#E5EAF0",
    borderRadius: 10,
    overflow: "hidden",
  },
  progressBarFill: {
    height: "100%",
    backgroundColor: "#4CAF50",
    borderRadius: 10,
  },
  payButton: {
    backgroundColor: "#4CAF50",
    borderRadius: 8,
    paddingVertical: 16,
    alignItems: "center",
    justifyContent: "center",
  },
  payButtonText: {
    fontSize: 16,
    fontWeight: "600",
    color: "#FFFFFF",
  },
});

export default MyPlanScreen;
