import React from "react";
import { View, Text, StyleSheet, Pressable } from "react-native";
import ChevronRight from "../../assets/icons/chevron_rightside.svg";

type Props = {
  totalWarrantyYears: number; // in years
  batteryPurchaseEpoch: number; // in seconds
};

const BatteryWarrantyCard: React.FC<Props> = ({
  totalWarrantyYears,
  batteryPurchaseEpoch,
}) => {
  const totalWarrantyMs = totalWarrantyYears * 365.25 * 24 * 60 * 60 * 1000;
  const purchaseDate = new Date(batteryPurchaseEpoch * 1000);
  const now = new Date();
  const elapsed = now.getTime() - purchaseDate.getTime();
  const remaining = Math.max(totalWarrantyMs - elapsed, 0);
  const progress = Math.min(elapsed / totalWarrantyMs, 1);

  const remainingDate = new Date(remaining);
  const yearsLeft = Math.floor(remaining / (365.25 * 24 * 60 * 60 * 1000));
  const monthsLeft = Math.floor(
    (remaining % (365.25 * 24 * 60 * 60 * 1000)) / (30.44 * 24 * 60 * 60 * 1000)
  );
  const daysLeft = Math.floor(
    (remaining % (30.44 * 24 * 60 * 60 * 1000)) / (24 * 60 * 60 * 1000)
  );

  return (
    <View style={styles.card}>
      <View style={styles.topRow}>
        <View style={styles.textColumn}>
          <Text style={styles.title}>Battery Warranty Left</Text>
          <Text style={styles.time}>
            {`${yearsLeft} years, ${monthsLeft} month${
              monthsLeft !== 1 ? "s" : ""
            }, ${daysLeft} day${daysLeft !== 1 ? "s" : ""}`}
          </Text>
        </View>
        <Pressable style={styles.iconButton}>
          <ChevronRight />
        </Pressable>
      </View>
      <View style={styles.progressContainer}>
        <View style={styles.progressBar}>
          <View
            style={[styles.progressFill, { width: `${(1 - progress) * 100}%` }]}
          />
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  card: {
    backgroundColor: "#FCFCFC",
    borderRadius: 10,
    padding: 16,
    width: "100%",
    height: 96,
    justifyContent: "space-between",
  },
  topRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "flex-start",
  },
  textColumn: {
    flexDirection: "column",
    gap: 4,
  },
  title: {
    fontSize: 12,
    fontFamily: "Inter-Medium",
    color: "#565E70",
    lineHeight: 16,
  },
  time: {
    fontSize: 14,
    fontFamily: "Inter-SemiBold",
    color: "#252A34",
    lineHeight: 20,
  },
  iconButton: {
    width: 40,
    height: 40,
    padding: 10,
    justifyContent: "center",
    alignItems: "center",
  },
  progressContainer: {
    marginTop: 8,
    width: "100%",
    height: 8,
  },
  progressBar: {
    width: "100%",
    height: 8,
    backgroundColor: "#E5E9F0",
    borderRadius: 10,
    overflow: "hidden",
  },
  progressFill: {
    height: "100%",
    backgroundColor: "#027A48",
    borderRadius: 10,
  },
});

export default BatteryWarrantyCard;
