import { useState, useEffect, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useAuth } from '@persona-community-5/auth';
import {
  Badge,
  Button,
  ArrowLeft,
  Loader2,
  ChevronLeft,
  ChevronRight,
  X,
} from '@persona-community-5/ui';

interface Persona {
  id: string;
  name: string;
  handle: string;
  gender: string;
  description: string;
  tags: string[];
  anchor_url?: string;
  avatar_url?: string;
  banner_url?: string;
  image_urls: string[];
  video_urls: string[];
  status: string;
  created_at: string;
}

const VIDEO_LABELS = [
  'Smile Reveal',
  'Personality Moment',
  'Lifestyle',
  'Invitation',
];

function ImageLightbox({
  images,
  initialIndex,
  onClose,
}: {
  images: string[];
  initialIndex: number;
  onClose: () => void;
}) {
  const [index, setIndex] = useState(initialIndex);

  useEffect(() => {
    const handleKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft') setIndex((i) => (i > 0 ? i - 1 : images.length - 1));
      if (e.key === 'ArrowRight') setIndex((i) => (i < images.length - 1 ? i + 1 : 0));
    };
    window.addEventListener('keydown', handleKey);
    return () => window.removeEventListener('keydown', handleKey);
  }, [images.length, onClose]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/90">
      <button
        type="button"
        onClick={onClose}
        className="absolute top-4 right-4 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
      >
        <X className="h-6 w-6 text-white" />
      </button>

      {images.length > 1 && (
        <>
          <button
            type="button"
            onClick={() => setIndex((i) => (i > 0 ? i - 1 : images.length - 1))}
            className="absolute left-4 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
          >
            <ChevronLeft className="h-6 w-6 text-white" />
          </button>
          <button
            type="button"
            onClick={() => setIndex((i) => (i < images.length - 1 ? i + 1 : 0))}
            className="absolute right-4 p-2 rounded-full bg-white/10 hover:bg-white/20 transition-colors"
          >
            <ChevronRight className="h-6 w-6 text-white" />
          </button>
        </>
      )}

      <img
        src={images[index]}
        alt={`Image ${index + 1}`}
        className="max-h-[90vh] max-w-[90vw] object-contain rounded-lg"
      />

      <div className="absolute bottom-4 text-sm text-white/60">
        {index + 1} / {images.length}
      </div>
    </div>
  );
}

export function PersonaDetailPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { getToken } = useAuth();
  const [persona, setPersona] = useState<Persona | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  const apiBaseUrl = import.meta.env.VITE_API_URL || '';

  const fetchPersona = useCallback(async () => {
    try {
      const token = await getToken();
      const res = await fetch(`${apiBaseUrl}/api/persona-api/personas/${id}`, {
        headers: token ? { Authorization: `Bearer ${token}` } : {},
      });
      if (!res.ok) {
        if (res.status === 404) throw new Error('Persona not found');
        throw new Error('Failed to load persona');
      }
      const json = await res.json();
      setPersona(json.data);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load persona');
    } finally {
      setLoading(false);
    }
  }, [apiBaseUrl, getToken, id]);

  useEffect(() => {
    fetchPersona();
  }, [fetchPersona]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="h-8 w-8 animate-spin text-[var(--accent)]" />
      </div>
    );
  }

  if (error || !persona) {
    return (
      <div className="flex flex-col items-center justify-center py-20 gap-4">
        <p className="text-sm text-[var(--error)]">{error || 'Persona not found'}</p>
        <Button variant="outline" onClick={() => navigate('/')}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      {/* Back button */}
      <Button variant="ghost" onClick={() => navigate('/')} className="mb-2">
        <ArrowLeft className="mr-2 h-4 w-4" />
        Back
      </Button>

      {/* Banner header */}
      <div className="relative rounded-xl overflow-hidden">
        <div className="h-48 md:h-64 bg-[var(--surface-200)]">
          {persona.banner_url && (
            <img
              src={persona.banner_url}
              alt=""
              className="h-full w-full object-cover"
            />
          )}
        </div>

        {/* Avatar centered */}
        <div className="flex justify-center -mt-16">
          <div className="relative h-32 w-32 rounded-full border-4 border-[var(--background)] bg-[var(--surface-300)] overflow-hidden">
            {persona.avatar_url ? (
              <img
                src={persona.avatar_url}
                alt={persona.name}
                className="h-full w-full object-cover"
              />
            ) : (
              <div className="h-full w-full flex items-center justify-center text-[var(--text-muted)] text-3xl font-bold">
                {persona.name?.charAt(0)?.toUpperCase() || '?'}
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Name + handle + tags */}
      <div className="text-center space-y-2">
        <h1 className="text-2xl font-bold text-[var(--text-primary)]">{persona.name}</h1>
        <p className="text-sm text-[var(--text-muted)]">@{persona.handle}</p>
        {persona.tags?.length > 0 && (
          <div className="flex flex-wrap justify-center gap-2 mt-3">
            {persona.tags.map((tag) => (
              <Badge key={tag} variant="secondary">
                {tag}
              </Badge>
            ))}
          </div>
        )}
        <p className="text-sm text-[var(--text-secondary)] max-w-xl mx-auto mt-4">
          {persona.description}
        </p>
      </div>

      {/* Image gallery */}
      {persona.image_urls?.length > 0 && (
        <div className="space-y-4">
          <h2 className="text-lg font-semibold text-[var(--text-primary)]">Gallery</h2>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
            {persona.image_urls.map((url, i) => (
              <button
                key={url}
                type="button"
                onClick={() => setLightboxIndex(i)}
                className="aspect-square rounded-lg overflow-hidden bg-[var(--surface-200)] hover:opacity-90 transition-opacity focus:outline-none focus:ring-2 focus:ring-[var(--accent)]"
              >
                <img
                  src={url}
                  alt={`${persona.name} image ${i + 1}`}
                  className="h-full w-full object-cover"
                />
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Videos section */}
      {persona.video_urls?.length > 0 && (
        <div className="space-y-4">
          <h2 className="text-lg font-semibold text-[var(--text-primary)]">Videos</h2>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {persona.video_urls.map((url, i) => (
              <div key={url} className="space-y-2">
                <p className="text-sm font-medium text-[var(--text-secondary)]">
                  {VIDEO_LABELS[i] || `Video ${i + 1}`}
                </p>
                <div className="rounded-lg overflow-hidden bg-[var(--surface-200)]">
                  <video
                    src={url}
                    controls
                    className="w-full"
                    preload="metadata"
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Lightbox */}
      {lightboxIndex !== null && (
        <ImageLightbox
          images={persona.image_urls}
          initialIndex={lightboxIndex}
          onClose={() => setLightboxIndex(null)}
        />
      )}
    </div>
  );
}
