"use client";

import { useEffect, useMemo, useRef, useState } from "react";
import { toPng } from "html-to-image";
import { getCountry } from "@/lib/countries";
import EsimServices from "./EsimServices";

type Contact = { name: string; relationship?: string | null; country?: string | null; phone: string };
type Doc = { type: string; title: string; fileUrl: string; assignmentId: string | null };
type ItItem = { time: string | null; title: string; location: string | null; description: string | null };
type ItDay = { title: string; date: string | null; items: ItItem[] };
type EmNum = { label: string; phone: string; country: string | null };

export type PubTrip = {
  id: string;
  assignmentId: string;
  name: string;
  originCountry: string | null;
  destinationCountry: string | null;
  startDate: string | null;
  endDate: string | null;
  currencyFrom: string | null;
  currencyTo: string | null;
  exchangeRate: number | null;
  cost: number;
  paid: number;
  itinerary: ItDay[];
  emergencyNumbers: EmNum[];
};

export type PubData = {
  traveler: {
    firstName: string;
    lastName: string;
    photoUrl: string | null;
    language: string;
    residenceCountry: string | null;
    bloodType: string | null;
    allergies: string | null;
    conditions: string | null;
    medications: string | null;
    medicalNotes: string | null;
    emergencyContacts: Contact[];
  };
  agency: { name: string; logoUrl: string | null; phone: string | null; whatsapp: string | null };
  trips: PubTrip[];
  documents: Doc[];
};

const TABS = [
  { id: "viajero", label: "Viajero", icon: "👤" },
  { id: "tickets", label: "Tickets", icon: "🎫" },
  { id: "itinerario", label: "Itinerario", icon: "📅" },
  { id: "traductor", label: "Traductor", icon: "🌐" },
  { id: "servicios", label: "Servicios", icon: "📶" },
  { id: "contacto", label: "Contacto", icon: "🆘" },
];

function money(n: number, c = "MXN") {
  try {
    return new Intl.NumberFormat("es-MX", { style: "currency", currency: c }).format(n);
  } catch {
    return `$${n.toFixed(2)}`;
  }
}

function Clock({ tz, label, flag }: { tz: string; label: string; flag: string }) {
  const [now, setNow] = useState<string>("");
  useEffect(() => {
    const fmt = new Intl.DateTimeFormat("es-MX", {
      timeZone: tz, hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: true,
    });
    const tick = () => setNow(fmt.format(new Date()));
    tick();
    const i = setInterval(tick, 1000);
    return () => clearInterval(i);
  }, [tz]);
  return (
    <div className="rounded-xl bg-white/10 px-3 py-2 text-center backdrop-blur">
      <div className="text-xs text-white/70">{flag} {label}</div>
      <div className="font-mono text-lg font-semibold text-white">{now}</div>
    </div>
  );
}

export default function PublicDashboard({ data }: { data: PubData }) {
  const [tab, setTab] = useState("viajero");
  const [tripId, setTripId] = useState(data.trips[0]?.id ?? "");
  const [ticketCat, setTicketCat] = useState<string | null>(null);
  const [fetchedRate, setFetchedRate] = useState<{ rate: number; date: string } | null>(null);
  const itineraryRef = useRef<HTMLDivElement>(null);
  const [downloadingImg, setDownloadingImg] = useState(false);

  const trip = useMemo(() => data.trips.find((t) => t.id === tripId), [data.trips, tripId]);
  const origin = getCountry(trip?.originCountry ?? data.traveler.residenceCountry);
  const destination = getCountry(trip?.destinationCountry);

  // Tasa manual asignada por la agencia (tiene prioridad).
  const manualRate = useMemo(
    () => (trip?.exchangeRate ? { rate: trip.exchangeRate, date: "Tasa de la agencia" } : null),
    [trip]
  );
  const fromCurrency = trip?.currencyFrom || origin?.currency || "";
  const toCurrency = trip?.currencyTo || destination?.currency || "";

  // Tipo de cambio diario automático (solo si no hay tasa manual).
  useEffect(() => {
    if (manualRate || !fromCurrency || !toCurrency) return;
    let active = true;
    fetch(`/api/exchange?from=${fromCurrency}&to=${toCurrency}`)
      .then((r) => r.json())
      .then((d) => {
        if (active && d.rate) setFetchedRate({ rate: d.rate, date: d.date });
      })
      .catch(() => {});
    return () => {
      active = false;
    };
  }, [manualRate, fromCurrency, toCurrency]);

  const rate = manualRate ?? fetchedRate;

  const tripDocs = data.documents.filter(
    (d) => !trip || d.assignmentId === trip.assignmentId || d.assignmentId === null
  );
  const ticketDocs = tripDocs;

  const ticketCats = [
    { id: "FLIGHT", label: "Vuelos", icon: "✈️" },
    { id: "TRAIN", label: "Transporte", icon: "🚌" },
    { id: "ENTRY", label: "Entradas", icon: "🎟️" },
    { id: "RESERVATION", label: "Hotel", icon: "🏨" },
    { id: "PASSPORT", label: "Pasaporte", icon: "🛂" },
    { id: "VISA", label: "Visa", icon: "📑" },
    { id: "INE", label: "INE", icon: "🪪" },
    { id: "LICENSE", label: "Licencia", icon: "🚗" },
    { id: "INSURANCE", label: "Seguros", icon: "🛡️" },
    { id: "OTHER", label: "Otros", icon: "📄" },
  ];

  const t = data.traveler;
  const fromCur = fromCurrency;
  const toCur = toCurrency;

  async function downloadItinerary() {
    if (!itineraryRef.current) return;
    setDownloadingImg(true);
    try {
      const dataUrl = await toPng(itineraryRef.current, {
        backgroundColor: "#f1f5f9",
        pixelRatio: 2,
        cacheBust: true,
        skipFonts: true,
      });
      const safeName = `${trip?.name ?? "viaje"}-${t.firstName}-${t.lastName}`
        .normalize("NFD")
        .replace(/[^\w.-]+/g, "_");
      const link = document.createElement("a");
      link.download = `itinerario-${safeName}.png`;
      link.href = dataUrl;
      link.click();
    } catch {
      alert("No se pudo generar la imagen. Intenta de nuevo.");
    } finally {
      setDownloadingImg(false);
    }
  }

  return (
    <div className="min-h-screen bg-slate-100 pb-24">
      {/* Header */}
      <header className="bg-gradient-to-br from-blue-600 to-indigo-700 px-4 pb-6 pt-5 text-white">
        <div className="mx-auto max-w-2xl">
          <div className="flex flex-wrap items-start justify-between gap-3">
            {/* Tipo de cambio */}
            <div className="rounded-xl bg-white/10 px-3 py-2 backdrop-blur">
              <div className="text-xs text-white/70">Tipo de cambio</div>
              <div className="flex items-center gap-1 text-sm font-semibold">
                <span>{origin?.flag}</span>
                <span>1 {fromCur}</span>
                <span className="text-white/60">=</span>
                <span>{destination?.flag}</span>
                <span>{rate ? `${rate.rate.toFixed(4)} ${toCur}` : "…"}</span>
              </div>
              {rate ? <div className="text-[10px] text-white/50">{rate.date}</div> : null}
            </div>
            <div className="flex flex-wrap justify-end gap-2">
              {origin ? <Clock tz={origin.timezone} label={origin.name} flag={origin.flag} /> : null}
              {destination ? <Clock tz={destination.timezone} label={destination.name} flag={destination.flag} /> : null}
            </div>
          </div>

          <div className="mt-5 flex items-center gap-4">
            {t.photoUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={t.photoUrl} alt="" className="h-16 w-16 rounded-full object-cover ring-2 ring-white/40" />
            ) : (
              <div className="flex h-16 w-16 items-center justify-center rounded-full bg-white/20 text-2xl font-bold">
                {t.firstName.charAt(0)}
              </div>
            )}
            <div>
              <h1 className="text-xl font-bold">{t.firstName} {t.lastName}</h1>
              <p className="text-sm text-white/80">{data.agency.name}</p>
            </div>
          </div>

          {data.trips.length > 0 ? (
            <select
              value={tripId}
              onChange={(e) => { setTripId(e.target.value); setTicketCat(null); }}
              className="mt-4 w-full rounded-lg border-0 bg-white/15 px-3 py-2 text-sm font-medium text-white backdrop-blur focus:ring-2 focus:ring-white/40"
            >
              {data.trips.map((tr) => (
                <option key={tr.id} value={tr.id} className="text-slate-900">
                  {tr.name}
                </option>
              ))}
            </select>
          ) : null}
        </div>
      </header>

      <main className="mx-auto max-w-2xl px-4 py-5">
        {/* Tab content */}
        {tab === "viajero" && (
          <div className="space-y-4">
            <Card title="Datos del viajero">
              <Grid>
                <Field k="Nombre" v={`${t.firstName} ${t.lastName}`} />
                <Field k="Residencia" v={`${origin?.flag ?? ""} ${origin?.name ?? "—"}`} />
                <Field k="Idioma" v={t.language.toUpperCase()} />
              </Grid>
            </Card>
            <Card title="🩺 Datos médicos">
              <Grid>
                <Field k="Tipo de sangre" v={t.bloodType ?? "—"} />
                <Field k="Alergias" v={t.allergies ?? "—"} />
                <Field k="Condiciones" v={t.conditions ?? "—"} />
                <Field k="Medicamentos" v={t.medications ?? "—"} />
              </Grid>
              {t.medicalNotes ? <p className="mt-2 text-sm text-slate-600">{t.medicalNotes}</p> : null}
            </Card>
            {trip ? (
              <Card title="💳 Estado de cuenta">
                <div className="grid grid-cols-3 gap-3 text-center">
                  <Box label="Costo" v={money(trip.cost)} />
                  <Box label="Pagado" v={money(trip.paid)} color="text-emerald-600" />
                  <Box label="Saldo" v={money(trip.cost - trip.paid)} color="text-amber-600" />
                </div>
              </Card>
            ) : null}
          </div>
        )}

        {tab === "tickets" && (
          <div className="space-y-4">
            {!ticketCat ? (
              <div className="grid grid-cols-2 gap-3">
                {ticketCats.map((c) => {
                  const count = ticketDocs.filter((d) => d.type === c.id).length;
                  return (
                    <button key={c.id} onClick={() => setTicketCat(c.id)} className="card flex flex-col items-center p-6 transition hover:shadow-md">
                      <span className="text-4xl">{c.icon}</span>
                      <span className="mt-2 font-semibold">{c.label}</span>
                      <span className="text-xs text-slate-400">{count} documento(s)</span>
                    </button>
                  );
                })}
              </div>
            ) : (
              <div>
                <button onClick={() => setTicketCat(null)} className="mb-3 text-sm text-blue-600">← Categorías</button>
                <DocList docs={ticketDocs.filter((d) => d.type === ticketCat)} empty="Sin documentos en esta categoría." />
              </div>
            )}
          </div>
        )}

        {tab === "servicios" && (
          <EsimServices
            defaultCountryCode={trip?.destinationCountry}
            travelerName={`${t.firstName} ${t.lastName}`}
          />
        )}

        {tab === "itinerario" && (
          <div className="space-y-4">
            {!trip || trip.itinerary.length === 0 ? (
              <Card title="📅 Itinerario"><p className="text-sm text-slate-400">Sin itinerario disponible.</p></Card>
            ) : (
              <>
                <button
                  onClick={downloadItinerary}
                  disabled={downloadingImg}
                  className="btn-primary w-full"
                >
                  {downloadingImg ? "Generando imagen…" : "⬇️ Descargar itinerario como imagen"}
                </button>
                <div ref={itineraryRef} className="space-y-4 rounded-2xl bg-slate-100 p-1">
                  <div className="rounded-2xl bg-gradient-to-br from-blue-600 to-indigo-700 p-4 text-white">
                    <div className="text-sm text-white/80">{data.agency.name}</div>
                    <div className="text-lg font-bold">{trip.name}</div>
                    <div className="text-xs text-white/70">
                      {origin?.flag} {origin?.name} → {destination?.flag} {destination?.name}
                    </div>
                    <div className="mt-1 text-xs text-white/70">{t.firstName} {t.lastName}</div>
                  </div>
                  {trip.itinerary.map((day, i) => (
                    <Card key={i} title={day.title} subtitle={day.date ? new Date(day.date).toLocaleDateString("es-MX", { weekday: "long", day: "numeric", month: "long" }) : undefined}>
                      <ol className="relative space-y-3 border-l-2 border-blue-100 pl-4">
                        {day.items.map((it, j) => (
                          <li key={j} className="relative">
                            <span className="absolute -left-[22px] top-1 h-3 w-3 rounded-full bg-blue-500" />
                            <div className="text-sm font-semibold">{it.time ? `${it.time} · ` : ""}{it.title}</div>
                            {it.location ? <div className="text-xs text-slate-500">📍 {it.location}</div> : null}
                            {it.description ? <div className="text-xs text-slate-500">{it.description}</div> : null}
                          </li>
                        ))}
                      </ol>
                    </Card>
                  ))}
                </div>
              </>
            )}
          </div>
        )}

        {tab === "traductor" && (
          <Card title="🌐 Traductor">
            <p className="mb-4 text-sm text-slate-500">
              Traduce de {origin?.name ?? "tu idioma"} a {destination?.name ?? "destino"}.
            </p>
            <a
              href={`https://translate.google.com/?sl=${t.language}&tl=${destination?.language ?? "en"}&op=translate`}
              target="_blank"
              rel="noreferrer"
              className="btn-primary w-full"
            >
              Abrir Google Traductor →
            </a>
          </Card>
        )}

        {tab === "contacto" && (
          <div className="space-y-4">
            <Card title="🏢 Tu agencia">
              <div className="space-y-2">
                {data.agency.whatsapp ? (
                  <a href={`https://wa.me/${data.agency.whatsapp.replace(/[^\d]/g, "")}`} target="_blank" rel="noreferrer" className="flex items-center gap-3 rounded-xl bg-emerald-50 p-3 text-emerald-700">
                    <span className="text-2xl">💬</span><span className="font-medium">WhatsApp con {data.agency.name}</span>
                  </a>
                ) : null}
                {data.agency.phone ? (
                  <a href={`tel:${data.agency.phone.replace(/\s/g, "")}`} className="flex items-center gap-3 rounded-xl bg-blue-50 p-3 text-blue-700">
                    <span className="text-2xl">📞</span><span className="font-medium">Llamar a la agencia</span>
                  </a>
                ) : null}
              </div>
            </Card>
            <Card title="🚨 Emergencias del destino">
              {trip && trip.emergencyNumbers.length > 0 ? (
                <div className="space-y-2">
                  {trip.emergencyNumbers.map((n, i) => (
                    <a key={i} href={`tel:${n.phone.replace(/\s/g, "")}`} className="flex items-center justify-between rounded-xl bg-red-50 p-3 text-red-700">
                      <span className="font-medium">{getCountry(n.country)?.flag ?? "🚨"} {n.label}</span>
                      <span className="font-mono font-bold">{n.phone}</span>
                    </a>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-slate-400">Sin números de emergencia para este viaje.</p>
              )}
            </Card>
            <Card title="📞 Mis contactos de emergencia">
              {t.emergencyContacts.length > 0 ? (
                <div className="space-y-2">
                  {t.emergencyContacts.map((c, i) => {
                    const dial = getCountry(c.country)?.dial ?? "";
                    const flag = getCountry(c.country)?.flag ?? "";
                    return (
                      <a key={i} href={`tel:${(dial + c.phone).replace(/[^\d+]/g, "")}`} className="flex items-center justify-between rounded-xl bg-slate-50 p-3">
                        <span className="font-medium">{c.name} {c.relationship ? <span className="text-slate-400">· {c.relationship}</span> : null}</span>
                        <span className="font-mono">{dial ? `${flag} ${dial} ` : ""}{c.phone}</span>
                      </a>
                    );
                  })}
                </div>
              ) : (
                <p className="text-sm text-slate-400">Sin contactos.</p>
              )}
            </Card>
          </div>
        )}
      </main>

      {/* Bottom nav */}
      <nav className="fixed inset-x-0 bottom-0 z-40 border-t border-slate-200 bg-white/95 backdrop-blur">
        <div className="mx-auto flex max-w-2xl justify-between px-2">
          {TABS.map((tb) => (
            <button
              key={tb.id}
              onClick={() => setTab(tb.id)}
              className={`flex flex-1 flex-col items-center gap-0.5 py-2 text-[11px] ${tab === tb.id ? "text-blue-600" : "text-slate-400"}`}
            >
              <span className="text-xl">{tb.icon}</span>
              {tb.label}
            </button>
          ))}
        </div>
      </nav>
    </div>
  );
}

function Card({ title, subtitle, children }: { title: string; subtitle?: string; children: React.ReactNode }) {
  return (
    <div className="card p-5">
      <h2 className="font-semibold">{title}</h2>
      {subtitle ? <p className="mb-2 text-xs capitalize text-slate-400">{subtitle}</p> : <div className="mb-2" />}
      {children}
    </div>
  );
}
function Grid({ children }: { children: React.ReactNode }) {
  return <div className="grid grid-cols-2 gap-3">{children}</div>;
}
function Field({ k, v }: { k: string; v: string }) {
  return (
    <div className="rounded-lg bg-slate-50 p-2">
      <div className="text-xs text-slate-400">{k}</div>
      <div className="text-sm font-medium">{v}</div>
    </div>
  );
}
function Box({ label, v, color = "text-slate-700" }: { label: string; v: string; color?: string }) {
  return (
    <div className="rounded-xl bg-slate-50 p-3">
      <div className={`text-base font-bold ${color}`}>{v}</div>
      <div className="text-xs text-slate-500">{label}</div>
    </div>
  );
}
function DocList({ docs, empty }: { docs: { title: string; fileUrl: string }[]; empty: string }) {
  if (docs.length === 0) return <p className="text-sm text-slate-400">{empty}</p>;
  return (
    <div className="space-y-2">
      {docs.map((d, i) => (
        <a key={i} href={d.fileUrl} target="_blank" rel="noreferrer" className="flex items-center justify-between rounded-xl bg-slate-50 p-3 text-sm">
          <span className="min-w-0 flex-1 truncate font-medium">{d.title}</span>
          <span className="ml-2 text-blue-600">Ver / descargar ↓</span>
        </a>
      ))}
    </div>
  );
}
