"use client";
import Link from "next/link";
import { useEffect, useMemo, useRef, useState } from "react";
import { Check, ImagePlus, Loader2, MapPin, Plus, Save, Trash2, Video } from "lucide-react";

import { Navbar } from "@/components/Navbar";
import { api } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import type { Genre, MediaItem, ServiceType } from "@/lib/types";
import { cn } from "@/lib/utils";

const CURRENCIES = ["USD", "CLP", "EUR"];

export default function MiPerfil() {
  const { user, loading: authLoading } = useAuth();

  const [serviceTypes, setServiceTypes] = useState<ServiceType[]>([]);
  const [genreList, setGenreList] = useState<Genre[]>([]);
  const [media, setMedia] = useState<MediaItem[]>([]);
  const [hasProfile, setHasProfile] = useState(false);
  const [profileId, setProfileId] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [msg, setMsg] = useState<string | null>(null);

  const [form, setForm] = useState({
    stage_name: "",
    bio: "",
    show_description: "",
    years_experience: "" as number | "",
    base_price: 0,
    currency: "USD",
    travel_radius_km: 25,
    city: "",
    country: "VE",
    service_types: [] as string[],
    genres: [] as string[],
  });
  const [customGenre, setCustomGenre] = useState("");
  const fileRef = useRef<HTMLInputElement>(null);
  const [videoUrl, setVideoUrl] = useState("");
  const [videoCaption, setVideoCaption] = useState("");

  useEffect(() => {
    if (authLoading || !user) return;
    Promise.all([api.serviceTypes(), api.genres(), api.myProfile()])
      .then(([st, gs, prof]) => {
        setServiceTypes(st);
        setGenreList(gs);
        if (prof) {
          setHasProfile(true);
          setProfileId(prof.id);
          setMedia(prof.media ?? []);
          setForm({
            stage_name: prof.stage_name,
            bio: prof.bio ?? "",
            show_description: prof.show_description ?? "",
            years_experience: prof.years_experience ?? "",
            base_price: prof.base_price,
            currency: prof.currency,
            travel_radius_km: prof.travel_radius_km,
            city: prof.city ?? "",
            country: prof.country,
            service_types: prof.service_types,
            genres: prof.genres,
          });
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [authLoading, user]);

  const grouped = useMemo(() => {
    const g: Record<string, ServiceType[]> = {};
    for (const s of serviceTypes) (g[s.group] ??= []).push(s);
    return g;
  }, [serviceTypes]);

  function toggle(key: "service_types" | "genres", value: string) {
    setForm((f) => {
      const has = f[key].includes(value);
      return { ...f, [key]: has ? f[key].filter((v) => v !== value) : [...f[key], value] };
    });
  }

  async function save() {
    setSaving(true);
    setMsg(null);
    try {
      const saved = await api.upsertProfile({
        stage_name: form.stage_name,
        bio: form.bio || null,
        show_description: form.show_description || null,
        years_experience: form.years_experience === "" ? null : Number(form.years_experience),
        service_types: form.service_types,
        genres: form.genres,
        base_price: Number(form.base_price),
        currency: form.currency,
        travel_radius_km: Number(form.travel_radius_km),
        city: form.city || null,
        country: form.country,
      });
      setHasProfile(true);
      setProfileId(saved.id);
      setMsg("Perfil guardado ✓");
    } catch (e) {
      setMsg(e instanceof Error ? e.message : "Error al guardar");
    } finally {
      setSaving(false);
    }
  }

  async function onPhoto(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    try {
      const item = await api.uploadPhoto(file);
      setMedia((m) => [...m, item]);
    } catch (err) {
      setMsg(err instanceof Error ? err.message : "Error al subir la foto");
    } finally {
      if (fileRef.current) fileRef.current.value = "";
    }
  }

  async function onAddVideo() {
    if (!videoUrl.trim()) return;
    try {
      const item = await api.addVideo({
        url: videoUrl.trim(),
        caption: videoCaption.trim() || undefined,
        is_featured: media.filter((m) => m.kind === "video").length === 0,
      });
      setMedia((m) => [...m, item]);
      setVideoUrl("");
      setVideoCaption("");
    } catch (err) {
      setMsg(err instanceof Error ? err.message : "Error al agregar el video");
    }
  }

  async function onDeleteMedia(id: number) {
    try {
      await api.deleteMedia(id);
      setMedia((m) => m.filter((x) => x.id !== id));
    } catch {
      /* noop */
    }
  }

  function useMyLocation() {
    navigator.geolocation?.getCurrentPosition(async (pos) => {
      try {
        await api.updateLocation({ lat: pos.coords.latitude, lng: pos.coords.longitude, is_available: true });
        setMsg("Ubicación actualizada · ahora estás disponible ✓");
      } catch (e) {
        setMsg(e instanceof Error ? e.message : "Error");
      }
    });
  }

  if (authLoading || (user && loading)) {
    return (
      <div className="min-h-screen">
        <Navbar />
        <div className="grid place-items-center py-32">
          <Loader2 className="animate-spin text-accent" />
        </div>
      </div>
    );
  }

  if (!user) {
    return (
      <div className="min-h-screen">
        <Navbar />
        <div className="mx-auto max-w-md px-4 py-24 text-center">
          <p className="text-ink-soft">Iniciá sesión para editar tu perfil de músico.</p>
          <Link href="/login" className="mt-4 inline-block rounded-xl bg-accent px-5 py-2.5 font-semibold text-white">
            Entrar
          </Link>
        </div>
      </div>
    );
  }

  const label = "mb-1.5 block text-[11px] font-semibold uppercase tracking-widest text-ink-mute";
  const input =
    "w-full rounded-xl border border-line bg-bg-card px-3 py-2.5 text-sm outline-none focus:border-accent";

  return (
    <div className="min-h-screen pb-24">
      <Navbar />
      <div className="mx-auto max-w-2xl px-4 py-8">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold tracking-tight">Mi perfil de músico</h1>
          {profileId && (
            <Link href={`/musico/${profileId}`} className="text-sm text-accent-deep hover:underline">
              Ver público
            </Link>
          )}
        </div>
        {msg && <p className="mt-2 text-sm font-medium text-accent-deep">{msg}</p>}

        {/* Datos básicos */}
        <section className="mt-6 space-y-4">
          <div>
            <label className={label}>Nombre artístico</label>
            <input className={input} value={form.stage_name}
              onChange={(e) => setForm({ ...form, stage_name: e.target.value })} placeholder="Ej: Mariachi Sol de América" />
          </div>
          <div>
            <label className={label}>Bio corta</label>
            <textarea className={cn(input, "min-h-[70px]")} value={form.bio}
              onChange={(e) => setForm({ ...form, bio: e.target.value })} placeholder="Quiénes son, qué hacen…" />
          </div>
          <div>
            <label className={label}>Nuestro espectáculo</label>
            <textarea className={cn(input, "min-h-[90px]")} value={form.show_description}
              onChange={(e) => setForm({ ...form, show_description: e.target.value })}
              placeholder="Duración, repertorio, qué incluye el show…" />
          </div>
          <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
            <div>
              <label className={label}>Precio desde</label>
              <input type="number" className={input} value={form.base_price}
                onChange={(e) => setForm({ ...form, base_price: Number(e.target.value) })} />
            </div>
            <div>
              <label className={label}>Moneda</label>
              <select className={input} value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value })}>
                {CURRENCIES.map((c) => <option key={c}>{c}</option>)}
              </select>
            </div>
            <div>
              <label className={label}>Años exp.</label>
              <input type="number" className={input} value={form.years_experience}
                onChange={(e) => setForm({ ...form, years_experience: e.target.value === "" ? "" : Number(e.target.value) })} />
            </div>
            <div>
              <label className={label}>Radio (km)</label>
              <input type="number" className={input} value={form.travel_radius_km}
                onChange={(e) => setForm({ ...form, travel_radius_km: Number(e.target.value) })} />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className={label}>Ciudad</label>
              <input className={input} value={form.city} onChange={(e) => setForm({ ...form, city: e.target.value })} />
            </div>
            <div>
              <label className={label}>País</label>
              <select className={input} value={form.country} onChange={(e) => setForm({ ...form, country: e.target.value })}>
                <option value="VE">Venezuela</option>
                <option value="CL">Chile</option>
                <option value="IE">Irlanda</option>
              </select>
            </div>
          </div>
        </section>

        {/* Tipos de servicio */}
        <section className="mt-8">
          <label className={label}>¿Qué ofrecés? (elegí uno o varios)</label>
          <div className="space-y-3">
            {Object.entries(grouped).map(([group, items]) => (
              <div key={group}>
                <div className="mb-1.5 text-xs text-ink-mute">{group}</div>
                <div className="flex flex-wrap gap-2">
                  {items.map((s) => {
                    const on = form.service_types.includes(s.slug);
                    return (
                      <button key={s.slug} onClick={() => toggle("service_types", s.slug)}
                        className={cn("rounded-full border px-3 py-1.5 text-[13px] transition-colors",
                          on ? "border-accent bg-accent text-white" : "border-line bg-bg-card text-ink-soft hover:border-accent/60")}>
                        {s.emoji} {s.name}
                      </button>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* Géneros */}
        <section className="mt-8">
          <label className={label}>Géneros / estilos (de la lista o escribí el tuyo)</label>
          <div className="flex flex-wrap gap-2">
            {genreList.map((g) => {
              const on = form.genres.includes(g.slug);
              return (
                <button key={g.slug} onClick={() => toggle("genres", g.slug)}
                  className={cn("rounded-full border px-3 py-1.5 text-[13px] transition-colors",
                    on ? "border-accent bg-accent/15 text-accent-deep" : "border-line bg-bg-card text-ink-soft hover:border-accent/60")}>
                  {on && <Check size={12} className="mr-1 inline" />}{g.name}
                </button>
              );
            })}
          </div>
          {/* Géneros libres agregados */}
          {form.genres.filter((g) => !genreList.some((x) => x.slug === g)).length > 0 && (
            <div className="mt-2 flex flex-wrap gap-2">
              {form.genres.filter((g) => !genreList.some((x) => x.slug === g)).map((g) => (
                <span key={g} className="inline-flex items-center gap-1 rounded-full border border-accent bg-accent/15 px-3 py-1.5 text-[13px] text-accent-deep">
                  {g}
                  <button onClick={() => toggle("genres", g)}><Trash2 size={12} /></button>
                </span>
              ))}
            </div>
          )}
          <div className="mt-3 flex gap-2">
            <input className={input} value={customGenre} onChange={(e) => setCustomGenre(e.target.value)}
              placeholder="Agregar otro género…" onKeyDown={(e) => {
                if (e.key === "Enter" && customGenre.trim()) {
                  if (!form.genres.includes(customGenre.trim())) toggle("genres", customGenre.trim());
                  setCustomGenre("");
                }
              }} />
            <button onClick={() => { if (customGenre.trim() && !form.genres.includes(customGenre.trim())) { toggle("genres", customGenre.trim()); setCustomGenre(""); } }}
              className="shrink-0 rounded-xl border border-line px-4 text-sm font-semibold hover:border-accent hover:text-accent-deep">
              <Plus size={16} />
            </button>
          </div>
        </section>

        {/* Disponibilidad */}
        <section className="mt-8 rounded-2xl border border-line bg-bg-card p-4">
          <div className="flex items-center justify-between gap-3">
            <div>
              <div className="text-sm font-semibold">Disponibilidad en vivo</div>
              <div className="text-xs text-ink-mute">Compartí tu ubicación para aparecer como disponible cerca.</div>
            </div>
            <button onClick={useMyLocation} disabled={!hasProfile}
              className="inline-flex shrink-0 items-center gap-2 rounded-xl bg-accent px-4 py-2 text-sm font-semibold text-white disabled:opacity-50">
              <MapPin size={15} /> Usar mi ubicación
            </button>
          </div>
        </section>

        {/* Media */}
        <section className="mt-8">
          <label className={label}>Portfolio (fotos y videos)</label>
          {!hasProfile && (
            <p className="mb-3 rounded-xl border border-dashed border-line p-3 text-center text-xs text-ink-mute">
              Guardá tu perfil primero para poder subir fotos y videos.
            </p>
          )}

          {media.length > 0 && (
            <div className="mb-3 grid grid-cols-3 gap-2">
              {media.map((m) => (
                <div key={m.id} className="group relative aspect-square overflow-hidden rounded-xl border border-line bg-bg-elev">
                  {m.kind === "photo" ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={m.url} alt="" className="h-full w-full object-cover" />
                  ) : (
                    <div className="grid h-full place-items-center text-center text-xs text-ink-soft">
                      <div><Video size={20} className="mx-auto mb-1 text-accent" />{m.provider}</div>
                    </div>
                  )}
                  {m.is_featured && (
                    <span className="absolute left-1.5 top-1.5 rounded bg-accent px-1.5 py-0.5 text-[10px] font-semibold text-white">★</span>
                  )}
                  <button onClick={() => onDeleteMedia(m.id)}
                    className="absolute right-1.5 top-1.5 grid h-6 w-6 place-items-center rounded-lg bg-white/90 text-red-500 opacity-0 transition-opacity group-hover:opacity-100">
                    <Trash2 size={13} />
                  </button>
                </div>
              ))}
            </div>
          )}

          <div className="flex flex-wrap gap-2">
            <button onClick={() => fileRef.current?.click()} disabled={!hasProfile}
              className="inline-flex items-center gap-2 rounded-xl border border-line px-4 py-2 text-sm font-semibold hover:border-accent hover:text-accent-deep disabled:opacity-50">
              <ImagePlus size={16} /> Subir foto
            </button>
            <input ref={fileRef} type="file" accept="image/jpeg,image/png,image/webp" hidden onChange={onPhoto} />
          </div>

          <div className="mt-3 flex flex-col gap-2 sm:flex-row">
            <input className={input} value={videoUrl} onChange={(e) => setVideoUrl(e.target.value)}
              placeholder="Link de video (YouTube, Instagram, TikTok…)" disabled={!hasProfile} />
            <input className={cn(input, "sm:max-w-[180px]")} value={videoCaption} onChange={(e) => setVideoCaption(e.target.value)}
              placeholder="Título (opcional)" disabled={!hasProfile} />
            <button onClick={onAddVideo} disabled={!hasProfile}
              className="shrink-0 inline-flex items-center gap-2 rounded-xl border border-line px-4 py-2 text-sm font-semibold hover:border-accent hover:text-accent-deep disabled:opacity-50">
              <Video size={16} /> Agregar
            </button>
          </div>
        </section>
      </div>

      {/* Barra fija guardar */}
      <div className="fixed inset-x-0 bottom-0 z-40 border-t border-line bg-bg/90 backdrop-blur-md">
        <div className="mx-auto flex max-w-2xl items-center justify-end px-4 py-3">
          <button onClick={save} disabled={saving || !form.stage_name.trim()}
            className="inline-flex items-center gap-2 rounded-xl bg-accent px-6 py-2.5 font-semibold text-white shadow-glow hover:bg-accent-deep disabled:opacity-50">
            {saving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />} Guardar perfil
          </button>
        </div>
      </div>
    </div>
  );
}
