import { Box, Button, Group, Stack, Text } from "@mantine/core";
import { CreditCard, Timer } from "lucide-react";
import { useEffect, useState } from "react";

import { CardTitle, SectionCard } from "./layout";

interface Remaining {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
  expired: boolean;
}

function getRemaining(deadlineMs: number): Remaining {
  const diff = deadlineMs - Date.now();
  if (diff <= 0) {
    return { days: 0, hours: 0, minutes: 0, seconds: 0, expired: true };
  }
  const totalSeconds = Math.floor(diff / 1000);
  return {
    days: Math.floor(totalSeconds / 86400),
    hours: Math.floor((totalSeconds % 86400) / 3600),
    minutes: Math.floor((totalSeconds % 3600) / 60),
    seconds: totalSeconds % 60,
    expired: false,
  };
}

function Segment({ value, label }: { value: number; label: string }) {
  return (
    <Stack gap={2} align="center" style={{ minWidth: 52 }}>
      <Text
        fz="28px"
        fw={800}
        c="#10202F"
        lh={1}
        style={{ fontVariantNumeric: "tabular-nums" }}
      >
        {String(value).padStart(2, "0")}
      </Text>
      <Text fz="10.5px" fw={700} c="#9AA8B5" tt="uppercase" className="tracking-[0.6px]">
        {label}
      </Text>
    </Stack>
  );
}

export function PaymentDeadlineCard({
  paymentDeadline,
  onPay,
  paying,
}: {
  /** ISO timestamp marking the end of the pay window. */
  paymentDeadline: string;
  onPay?: () => void;
  paying?: boolean;
}) {
  const deadlineMs = new Date(paymentDeadline).getTime();
  const [remaining, setRemaining] = useState<Remaining>(() => getRemaining(deadlineMs));

  useEffect(() => {
    setRemaining(getRemaining(deadlineMs));
    const interval = setInterval(() => {
      const next = getRemaining(deadlineMs);
      setRemaining(next);
      if (next.expired) clearInterval(interval);
    }, 1000);
    return () => clearInterval(interval);
  }, [deadlineMs]);

  const accentBg = remaining.expired ? "#FBEAE7" : "#FEF6E6";
  const accentFg = remaining.expired ? "#C0392B" : "#B07D14";

  return (
    <SectionCard
      p={22}
      style={
        remaining.expired
          ? undefined
          : { borderColor: "#F2E4C4", boxShadow: "0 0 0 1px #FBEAC2" }
      }
    >
      <Group justify="space-between" align="center">
        <CardTitle>Payment deadline</CardTitle>
        <Group
          component="span"
          gap={6}
          align="center"
          wrap="nowrap"
          style={{
            display: "inline-flex",
            borderRadius: 999,
            padding: "5px 11px",
            fontSize: 11.5,
            fontWeight: 700,
            backgroundColor: accentBg,
            color: accentFg,
          }}
        >
          <Timer size={13} />
          {remaining.expired ? "Expired" : "Pay window open"}
        </Group>
      </Group>

      {remaining.expired ? (
        <Text mt={14} fz="13.5px" c="#6B7C8E">
          The payment window has closed. Move this booking to another schedule or
          contact support.
        </Text>
      ) : (
        <>
          <Group justify="space-between" mt={16} wrap="nowrap" px={4}>
            <Segment value={remaining.days} label="Days" />
            <Segment value={remaining.hours} label="Hrs" />
            <Segment value={remaining.minutes} label="Min" />
            <Segment value={remaining.seconds} label="Sec" />
          </Group>
          <Text mt={14} fz="12.5px" c="#9AA8B5" ta="center">
            Complete payment before the window closes to secure your slot.
          </Text>
          {onPay && (
            <Button
              fullWidth
              mt={16}
              radius={10}
              color="edr-green"
              leftSection={<CreditCard size={17} />}
              onClick={onPay}
              loading={paying}
              styles={{ root: { height: 46 }, label: { fontSize: 13.5, fontWeight: 700 } }}
            >
              Pay now
            </Button>
          )}
        </>
      )}

      <Box mt={16} h={1} w="100%" bg="#EEF2F6" />
      <Text mt={12} fz="12px" c="#9AA8B5">
        Deadline:{" "}
        {new Date(paymentDeadline).toLocaleString(undefined, {
          month: "short",
          day: "numeric",
          hour: "2-digit",
          minute: "2-digit",
        })}
      </Text>
    </SectionCard>
  );
}
