'use client';

import React, { useState, useEffect } from 'react';
import { HazardReport } from '@/types/hazard';
import {
  ChevronLeft,
  ChevronRight,
  AlertTriangle,
  Radio,
  ShieldCheck,
  MapPin,
  ExternalLink,
} from 'lucide-react';

interface AlertSliderProps {
  reports: HazardReport[];
  compact?: boolean;
  onSelectReport?: (report: HazardReport) => void;
  onOpenReportModal?: () => void;
}

interface SlideItem {
  id: string;
  badge: string;
  severity: 'darurat' | 'tinggi' | 'sedang' | 'info';
  title: string;
  description: string;
  village: string;
  timestamp: string;
  locationUrl?: string;
  report?: HazardReport;
}

const STATIC_SLIDES: SlideItem[] = [
  {
    id: 'adv-1',
    badge: 'HIMBAUAN RESMI POSKO',
    severity: 'tinggi',
    title: 'Waspada Cuaca Ekstrem & Genangan di 13 Desa Kecamatan Pulokulon',
    description:
      'Masyarakat di sekitar saluran irigasi dan bantaran sungai diimbau memantau ketinggian air, membersihkan drainase, dan menyiapkan tas siaga bencana.',
    village: 'Kecamatan Pulokulon',
    timestamp: 'Siaga 24 Jam',
  },
  {
    id: 'adv-2',
    badge: 'PROSEDUR DARURAT',
    severity: 'info',
    title: 'Aktifkan GPS Saat Melapor Agar Tim Posko Dapat Melacak Lokasi Akurat',
    description:
      'Setiap laporan warga kini otomatis menyertakan koordinat GPS dan tautan Google Maps agar tim Damkar, BPBD, dan Polsek cepat tiba di lokasi.',
    village: '13 Desa Terintegrasi',
    timestamp: 'SiapJaga v2.5',
  },
];

export default function AlertSlider({
  reports,
  compact = false,
  onSelectReport,
  onOpenReportModal,
}: AlertSliderProps) {
  const reportSlides: SlideItem[] = reports
    .filter((r) => r.status !== 'selesai')
    .slice(0, 4)
    .map((r) => ({
      id: r.id,
      badge: `${r.type.replace('_', ' ').toUpperCase()} • ${r.severity.toUpperCase()}`,
      severity: r.severity === 'rendah' ? 'info' : r.severity,
      title: r.title,
      description: r.description,
      village: r.village,
      timestamp: r.timestamp,
      locationUrl: r.locationUrl || `https://www.google.com/maps?q=${r.coordinates.lat},${r.coordinates.lng}`,
      report: r,
    }));

  const slides = reportSlides.length > 0 ? [...reportSlides, ...STATIC_SLIDES] : STATIC_SLIDES;
  const [currentIndex, setCurrentIndex] = useState(0);

  useEffect(() => {
    if (slides.length <= 1) return;
    const timer = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % slides.length);
    }, 5500);
    return () => clearInterval(timer);
  }, [slides.length]);

  const safeIndex = currentIndex % slides.length;
  const active = slides[safeIndex];

  const handlePrev = () => {
    setCurrentIndex((prev) => (prev - 1 + slides.length) % slides.length);
  };

  const handleNext = () => {
    setCurrentIndex((prev) => (prev + 1) % slides.length);
  };

  const gradientClass =
    active.severity === 'darurat'
      ? 'from-red-950/95 via-red-900/75 to-zinc-950 border-red-700/70'
      : active.severity === 'tinggi'
        ? 'from-orange-950/90 via-red-950/70 to-zinc-950 border-orange-700/60'
        : active.severity === 'sedang'
          ? 'from-amber-950/80 via-zinc-900 to-zinc-950 border-amber-700/50'
          : 'from-slate-900 via-zinc-900 to-slate-950 border-slate-700/70';

  const badgeClass =
    active.severity === 'darurat'
      ? 'bg-red-600 text-white'
      : active.severity === 'tinggi'
        ? 'bg-orange-600 text-white'
        : active.severity === 'sedang'
          ? 'bg-amber-500 text-zinc-950'
          : 'bg-sky-600 text-white';

  return (
    <div
      className={`relative rounded-2xl border bg-gradient-to-r ${gradientClass} overflow-hidden shadow-xl transition-all ${
        compact ? 'p-4' : 'p-6 sm:p-8'
      }`}
    >
      <div className="absolute -right-10 -top-10 w-44 h-44 bg-red-600/15 rounded-full blur-3xl pointer-events-none" />

      <div className="relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="space-y-2 max-w-3xl">
          <div className="flex flex-wrap items-center gap-2">
            <span
              className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-md text-[10px] font-black tracking-wider uppercase ${badgeClass}`}
            >
              {active.severity === 'darurat' ? (
                <Radio className="w-3 h-3 animate-pulse" />
              ) : active.severity === 'info' ? (
                <ShieldCheck className="w-3 h-3" />
              ) : (
                <AlertTriangle className="w-3 h-3" />
              )}
              {active.badge}
            </span>
            <span className="inline-flex items-center gap-1 text-[11px] text-zinc-300 font-medium">
              <MapPin className="w-3 h-3 text-red-400" />
              {active.village}
            </span>
            <span className="text-[11px] font-mono text-zinc-400">• {active.timestamp}</span>
          </div>

          <h3
            className={`font-black text-white leading-snug ${
              compact ? 'text-base' : 'text-xl sm:text-2xl'
            }`}
          >
            {active.title}
          </h3>
          <p className={`text-zinc-300 leading-relaxed ${compact ? 'text-xs line-clamp-2' : 'text-sm'}`}>
            {active.description}
          </p>
        </div>

        <div className="flex items-center gap-2 shrink-0">
          {active.report && onSelectReport && (
            <button
              type="button"
              onClick={() => onSelectReport(active.report!)}
              className="px-3.5 py-2 bg-white/10 hover:bg-white/20 border border-white/15 text-white text-xs font-bold rounded-xl transition cursor-pointer"
            >
              Lihat Detail
            </button>
          )}
          {active.locationUrl && (
            <a
              href={active.locationUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="px-3.5 py-2 bg-red-600 hover:bg-red-500 text-white text-xs font-bold rounded-xl transition inline-flex items-center gap-1.5"
            >
              <ExternalLink className="w-3.5 h-3.5" />
              Lacak Lokasi
            </a>
          )}
          {!active.report && onOpenReportModal && (
            <button
              type="button"
              onClick={onOpenReportModal}
              className="px-3.5 py-2 bg-red-600 hover:bg-red-500 text-white text-xs font-bold rounded-xl transition cursor-pointer"
            >
              Buat Laporan
            </button>
          )}

          <div className="flex items-center gap-1 ml-1">
            <button
              type="button"
              onClick={handlePrev}
              aria-label="Slide sebelumnya"
              className="p-2 bg-black/40 hover:bg-black/60 border border-white/10 rounded-lg text-zinc-200 transition cursor-pointer"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>
            <button
              type="button"
              onClick={handleNext}
              aria-label="Slide berikutnya"
              className="p-2 bg-black/40 hover:bg-black/60 border border-white/10 rounded-lg text-zinc-200 transition cursor-pointer"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* Slide Dots */}
      <div className="relative z-10 flex items-center gap-1.5 mt-4">
        {slides.map((s, idx) => (
          <button
            key={s.id}
            type="button"
            onClick={() => setCurrentIndex(idx)}
            aria-label={`Pilih slide ${idx + 1}`}
            className={`h-1.5 rounded-full transition-all cursor-pointer ${
              idx === safeIndex ? 'w-7 bg-red-500' : 'w-2 bg-white/25 hover:bg-white/40'
            }`}
          />
        ))}
      </div>
    </div>
  );
}
