"use client";

import { useEffect, useState } from "react";
import BottomNav from "@/components/BottomNav";
import AppHeader from "@/components/AppHeader";
import { Sun, Moon, Sunrise, Sunset, Clock, ChevronDown, ChevronUp, CheckCircle2, Car, Droplets, Accessibility } from "lucide-react";

interface PrayerTimings {
  Fajr: string;
  Sunrise: string;
  Dhuhr: string;
  Asr: string;
  Maghrib: string;
  Isha: string;
}

interface IqamaTimings {
  Fajr: string;
  Dhuhr: string;
  Asr: string;
  Maghrib: string;
  Isha: string;
}

interface MosqueFeatures {
  womenSpace: boolean;
  janazaPrayer: boolean;
  aidPrayer: boolean;
  childrenCourses: boolean;
  adultCourses: boolean;
  ramadanMeal: boolean;
  handicapAccessibility: boolean;
  ablutions: boolean;
  parking: boolean;
}

const prayerInfo = [
  { key: "Fajr", label: "Fajr", arabic: "الفجر", icon: Moon, gradient: "from-indigo-500 to-purple-600", hasIqama: true },
  { key: "Sunrise", label: "Shurûq", arabic: "الشروق", icon: Sunrise, gradient: "from-orange-400 to-amber-500", hasIqama: false },
  { key: "Dhuhr", label: "Dhuhr", arabic: "الظهر", icon: Sun, gradient: "from-amber-400 to-yellow-500", hasIqama: true },
  { key: "Asr", label: "Asr", arabic: "العصر", icon: Sun, gradient: "from-orange-500 to-red-500", hasIqama: true },
  { key: "Maghrib", label: "Maghrib", arabic: "المغرب", icon: Sunset, gradient: "from-red-500 to-purple-600", hasIqama: true },
  { key: "Isha", label: "Isha", arabic: "العشاء", icon: Moon, gradient: "from-purple-600 to-indigo-800", hasIqama: true },
];

export default function PrayerTimesPage() {
  const [timings, setTimings] = useState<PrayerTimings | null>(null);
  const [iqama, setIqama] = useState<IqamaTimings | null>(null);
  const [iqamaEnabled, setIqamaEnabled] = useState(false);
  const [jumua, setJumua] = useState("");
  const [features, setFeatures] = useState<MosqueFeatures | null>(null);
  const [currentPrayer, setCurrentPrayer] = useState("");
  const [loading, setLoading] = useState(true);
  const [showWidget, setShowWidget] = useState(false);

  useEffect(() => {
    fetch("/api/prayer-times")
      .then((r) => r.json())
      .then((data) => {
        if (data.error) return;
        setTimings(data.timings);
        setIqama(data.iqama);
        setIqamaEnabled(data.iqamaEnabled);
        setJumua(data.jumua);
        setFeatures(data.features);

        const now = new Date();
        const mins = now.getHours() * 60 + now.getMinutes();
        const times = data.timings;
        const toMins = (t: string) => {
          if (!t) return 0;
          const [h, m] = t.split(":").map(Number);
          return h * 60 + m;
        };

        if (mins >= toMins(times.Isha)) setCurrentPrayer("Isha");
        else if (mins >= toMins(times.Maghrib)) setCurrentPrayer("Maghrib");
        else if (mins >= toMins(times.Asr)) setCurrentPrayer("Asr");
        else if (mins >= toMins(times.Dhuhr)) setCurrentPrayer("Dhuhr");
        else if (mins >= toMins(times.Sunrise)) setCurrentPrayer("Sunrise");
        else if (mins >= toMins(times.Fajr)) setCurrentPrayer("Fajr");
        else setCurrentPrayer("Isha");
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  return (
    <div className="pb-20">
      <AppHeader title="Bönetider" />

      {/* Date info */}
      <div className="px-4 py-3 bg-emerald-mosque/5 border-b border-emerald-mosque/10 flex items-center justify-between">
        <p className="text-sm text-gray-700">
          {new Date().toLocaleDateString("sv-SE", { weekday: "long", year: "numeric", month: "long", day: "numeric" })}
        </p>
        <a
          href="https://mawaqit.net/en/stenhagensmoske-uppsala-75266-sweden"
          target="_blank"
          rel="noopener noreferrer"
          className="text-xs text-emerald-mosque font-medium"
        >
          mawaqit.net
        </a>
      </div>

      {/* Prayer Cards */}
      <div className="px-4 mt-3 space-y-2.5">
        {loading ? (
          Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="w-12 h-12 skeleton rounded-xl" />
                  <div><div className="h-4 skeleton rounded w-16 mb-1" /><div className="h-3 skeleton rounded w-10" /></div>
                </div>
                <div className="h-7 skeleton rounded w-16" />
              </div>
            </div>
          ))
        ) : (
          prayerInfo.map((prayer) => {
            const isActive = currentPrayer === prayer.key;
            const adhan = timings?.[prayer.key as keyof PrayerTimings] || "";
            const iqamaTime = prayer.hasIqama && iqamaEnabled ? iqama?.[prayer.key as keyof IqamaTimings] || "" : "";
            const Icon = prayer.icon;
            if (prayer.key === "Sunrise" && !adhan) return null;

            return (
              <div
                key={prayer.key}
                className={`rounded-2xl p-4 shadow-sm border transition-all ${
                  isActive ? "bg-emerald-mosque text-white border-emerald-mosque shadow-lg pulse-glow" :
                  prayer.key === "Sunrise" ? "bg-gray-50 border-gray-100 opacity-75" : "bg-white border-gray-100"
                }`}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <div className={`w-12 h-12 rounded-xl flex items-center justify-center bg-gradient-to-br ${isActive ? "from-white/20 to-white/10" : prayer.gradient}`}>
                      <Icon size={22} className="text-white" />
                    </div>
                    <div>
                      <h3 className={`font-bold text-base ${isActive ? "text-white" : "text-gray-900"}`}>{prayer.label}</h3>
                      <p className={`text-sm ${isActive ? "text-white/70" : "text-gray-400"}`}>{prayer.arabic}</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className={`text-2xl font-bold tabular-nums ${isActive ? "text-white" : "text-gray-900"}`}>{adhan || "--:--"}</p>
                    {iqamaTime && (
                      <p className={`text-xs font-medium mt-0.5 ${isActive ? "text-gold-light" : "text-emerald-mosque"}`}>Iqama: {iqamaTime}</p>
                    )}
                    {isActive && <p className="text-[10px] text-gold-light font-medium uppercase tracking-wider mt-0.5">Aktuell</p>}
                  </div>
                </div>
              </div>
            );
          })
        )}
      </div>

      {/* Jumu'ah */}
      {jumua && (
        <div className="px-4 mt-4">
          <div className="bg-emerald-mosque/5 rounded-2xl p-4 border border-emerald-mosque/20 flex items-start gap-3">
            <Clock size={22} className="text-emerald-mosque flex-shrink-0 mt-0.5" />
            <div>
              <h3 className="font-bold text-gray-900 text-sm">Fredagsbön (Jumu&apos;ah)</h3>
              <p className="text-lg font-bold text-emerald-mosque tabular-nums mt-0.5">{jumua}</p>
            </div>
          </div>
        </div>
      )}

      {/* Mawaqit Widget Toggle */}
      <div className="px-4 mt-4">
        <button
          onClick={() => setShowWidget(!showWidget)}
          className="w-full flex items-center justify-between p-4 bg-white rounded-2xl border border-gray-200 shadow-sm"
        >
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-xl bg-emerald-mosque/10 flex items-center justify-center">
              <Clock size={20} className="text-emerald-mosque" />
            </div>
            <div className="text-left">
              <h3 className="font-bold text-sm text-gray-900">Mawaqit tidtabell</h3>
              <p className="text-xs text-gray-500">Fullständig vy</p>
            </div>
          </div>
          {showWidget ? <ChevronUp size={20} className="text-gray-400" /> : <ChevronDown size={20} className="text-gray-400" />}
        </button>

        {showWidget && (
          <div className="mt-2 rounded-2xl overflow-hidden border border-gray-200 shadow-lg animate-fade-in">
            <iframe
              src="//mawaqit.net/en/w/stenhagensmoske-uppsala-75266-sweden?showOnly5PrayerTimes=0"
              frameBorder="0"
              scrolling="no"
              className="w-full"
              style={{ height: "450px", border: "none" }}
              title="Mawaqit Bönetider"
            />
          </div>
        )}
      </div>

      {/* Features */}
      {features && (
        <div className="px-4 mt-4">
          <h3 className="font-bold text-gray-900 text-sm mb-2">Moskéns faciliteter</h3>
          <div className="flex flex-wrap gap-1.5">
            {[
              { key: "womenSpace", label: "Damavdelning", icon: "👩" },
              { key: "janazaPrayer", label: "Janaza", icon: "🕊️" },
              { key: "aidPrayer", label: "Eid-bön", icon: "🌙" },
              { key: "childrenCourses", label: "Barnkurser", icon: "📚" },
              { key: "adultCourses", label: "Vuxenkurser", icon: "🎓" },
              { key: "ramadanMeal", label: "Iftar", icon: "🍽️" },
            ].filter((f) => features[f.key as keyof MosqueFeatures]).map((feat) => (
              <span key={feat.key} className="inline-flex items-center gap-1 px-2.5 py-1 bg-emerald-mosque/5 border border-emerald-mosque/15 rounded-full text-xs font-medium text-gray-700">
                {feat.icon} {feat.label}
              </span>
            ))}
            {features.parking && (
              <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-blue-50 rounded-full text-xs font-medium text-blue-700">
                <Car size={11} /> Parkering
              </span>
            )}
            {features.ablutions && (
              <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-cyan-50 rounded-full text-xs font-medium text-cyan-700">
                <Droplets size={11} /> Tvagning
              </span>
            )}
            {features.handicapAccessibility && (
              <span className="inline-flex items-center gap-1 px-2.5 py-1 bg-purple-50 rounded-full text-xs font-medium text-purple-700">
                <Accessibility size={11} /> Tillgängligt
              </span>
            )}
          </div>
        </div>
      )}

      <div className="px-4 mt-4 mb-4">
        <p className="text-[10px] text-gray-400 text-center">
          Bönetider via <a href="https://mawaqit.net/en/stenhagensmoske-uppsala-75266-sweden" target="_blank" rel="noopener noreferrer" className="text-emerald-mosque underline">Mawaqit</a> • Stenhagens Moské, Uppsala
        </p>
      </div>

      <BottomNav />
    </div>
  );
}
