"use client";

import { useEffect, useMemo, useState } from "react";

const BERLIN_TIME_ZONE = "Europe/Berlin";
const MATCH_COPY = "Your local time matches mine! No issues there.";

function getTimeZoneOffsetMinutes(date: Date, timeZone: string) {
  const formatter = new Intl.DateTimeFormat("en-US", {
    timeZone,
    hour12: false,
    hourCycle: "h23",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });

  const parts = formatter.formatToParts(date);
  const values = parts.reduce<Record<string, string>>((acc, part) => {
    if (part.type !== "literal") acc[part.type] = part.value;
    return acc;
  }, {});

  const asUTC = Date.UTC(
    Number(values.year),
    Number(values.month) - 1,
    Number(values.day),
    Number(values.hour),
    Number(values.minute),
    Number(values.second),
  );

  return (asUTC - date.getTime()) / 60000;
}

export function TimezoneClockBlock({ warningThresholdHours = 5 }: { warningThresholdHours?: number }) {
  const [now, setNow] = useState<Date | null>(null);

  const localFormatter = useMemo(
    () =>
      new Intl.DateTimeFormat("en-GB", {
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false,
      }),
    [],
  );

  const berlinFormatter = useMemo(
    () =>
      new Intl.DateTimeFormat("en-GB", {
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: false,
        timeZone: BERLIN_TIME_ZONE,
      }),
    [],
  );

  useEffect(() => {
    const updateNow = () => setNow(new Date());

    updateNow();
    const interval = setInterval(updateNow, 1000);
    return () => clearInterval(interval);
  }, []);

  const localTime = now ? localFormatter.format(now) : "";
  const berlinTime = now ? berlinFormatter.format(now) : "";
  const clocksMatch = localTime !== "" && localTime === berlinTime;
  const timeGapHours =
    now === null
      ? 0
      : Math.abs(
          getTimeZoneOffsetMinutes(now, BERLIN_TIME_ZONE) + now.getTimezoneOffset(),
        ) / 60;

  return (
    <div className="pt-3 flex flex-col items-center gap-3 px-4">
      <p className="text-[11px] uppercase tracking-[0.3em] text-gray-500">Time</p>
      
      {clocksMatch && (
        <div className="rounded-2xl border border-emerald-400/30 bg-emerald-500/10 px-4 py-3 backdrop-blur-sm shadow-lg text-center">
          <p className="text-sm font-semibold text-emerald-100">{MATCH_COPY}</p>
        </div>
      )}

      {!clocksMatch && timeGapHours >= warningThresholdHours && (
        <div className="flex flex-col items-center gap-1.5 rounded-2xl border border-amber-500/30 bg-amber-500/10 px-5 py-4 backdrop-blur-sm shadow-lg max-w-sm text-center">
          <p className="text-sm font-bold text-amber-400">
            Large Time Gap ({Math.round(timeGapHours)}h)
          </p>
          <p className="text-xs font-medium text-amber-200/80 leading-relaxed">
            Because we have a {Math.round(timeGapHours)}-hour time difference, our waking hours might barely overlap. Please expect delayed responses!
          </p>
        </div>
      )}

      <div className="flex flex-wrap items-stretch justify-center gap-3">
        <div className="relative w-full max-w-[11rem] rounded-2xl border border-white/15 bg-white/5 px-4 py-3 shadow-lg backdrop-blur-sm sm:w-auto">
          <div className="absolute right-0 top-1/2 h-0 w-0 -translate-y-1/2 translate-x-2 border-b-8 border-b-transparent border-l-8 border-l-white/15 border-t-8 border-t-transparent" />
          <p className="text-[11px] uppercase tracking-[0.24em] text-gray-400">
            Local time
          </p>
          <p className="mt-1 font-mono text-sm font-semibold text-gray-100">
            {localTime}
          </p>
        </div>

        <div className="relative w-full max-w-[11rem] rounded-2xl border border-white/15 bg-white/5 px-4 py-3 shadow-lg backdrop-blur-sm sm:w-auto">
          <div className="absolute left-0 top-1/2 h-0 w-0 -translate-x-2 -translate-y-1/2 border-b-8 border-b-transparent border-r-8 border-r-white/15 border-t-8 border-t-transparent" />
          <p className="text-[11px] uppercase tracking-[0.24em] text-gray-400">
            My time
          </p>
          <p className="mt-1 font-mono text-sm font-semibold text-gray-100">
            {berlinTime}
          </p>
        </div>
      </div>
    </div>
  );
}
