import { useState, useEffect } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { apiFetch, ApiError } from '../lib/api';

interface Video {
  id: string;
  title: string;
  thumbnailUrl: string | null;
  duration: number | null;
}

interface Playlist {
  id: string;
  title: string;
  description: string | null;
  visibility: 'private' | 'shared' | 'public';
}

interface PlaylistResponse {
  success: boolean;
  data: {
    playlist: Playlist;
    videos: Video[];
    permission: 'owner' | 'view' | 'edit';
  };
}

export default function PlaylistPage() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [data, setData] = useState<PlaylistResponse['data'] | null>(null);
  const [error, setError] = useState<'forbidden' | 'not_found' | null>(null);
  const [loading, setLoading] = useState(true);
  const [actionError, setActionError] = useState<string | null>(null);

  // Edit inline form
  const [editOpen, setEditOpen] = useState(false);
  const [editTitle, setEditTitle] = useState('');
  const [editVisibility, setEditVisibility] = useState<'private' | 'shared' | 'public'>('private');
  const [saving, setSaving] = useState(false);

  // Share modal
  const [shareOpen, setShareOpen] = useState(false);
  const [shareUserId, setShareUserId] = useState('');
  const [sharePermission, setSharePermission] = useState<'view' | 'edit'>('view');
  const [sharing, setSharing] = useState(false);
  const [shareError, setShareError] = useState<string | null>(null);
  const [shareOk, setShareOk] = useState(false);

  useEffect(() => {
    if (!id) return;
    apiFetch<PlaylistResponse>(`/playlists/${id}`)
      .then((res) => setData(res.data))
      .catch((err: unknown) => {
        if (err instanceof ApiError && err.status === 403) setError('forbidden');
        else setError('not_found');
      })
      .finally(() => setLoading(false));
  }, [id]);

  function openEdit() {
    if (!data) return;
    setEditTitle(data.playlist.title);
    setEditVisibility(data.playlist.visibility);
    setEditOpen(true);
    setActionError(null);
  }

  async function handleEdit(e: React.FormEvent) {
    e.preventDefault();
    if (!id || saving) return;
    setSaving(true);
    setActionError(null);
    try {
      const res = await apiFetch<{ success: boolean; data: { playlist: Playlist } }>(
        `/playlists/${id}`,
        { method: 'PATCH', body: JSON.stringify({ title: editTitle.trim(), visibility: editVisibility }) }
      );
      setData((prev) => prev ? { ...prev, playlist: res.data.playlist } : prev);
      setEditOpen(false);
    } catch {
      setActionError('Impossible de modifier la playlist.');
    }
    setSaving(false);
  }

  async function handleDelete() {
    if (!id || !confirm('Supprimer cette playlist ?')) return;
    setActionError(null);
    try {
      await apiFetch(`/playlists/${id}`, { method: 'DELETE' });
      navigate('/playlists');
    } catch {
      setActionError('Impossible de supprimer la playlist.');
    }
  }

  async function handleRemoveVideo(videoId: string) {
    if (!id || !confirm('Retirer cette vidéo de la playlist ?')) return;
    setActionError(null);
    try {
      await apiFetch(`/playlists/${id}/videos/${videoId}`, { method: 'DELETE' });
      setData((prev) => prev ? { ...prev, videos: prev.videos.filter((v) => v.id !== videoId) } : prev);
    } catch {
      setActionError('Impossible de retirer la vidéo.');
    }
  }

  async function handleShare(e: React.FormEvent) {
    e.preventDefault();
    if (!id || !shareUserId.trim() || sharing) return;
    setSharing(true);
    setShareError(null);
    setShareOk(false);
    try {
      await apiFetch(`/playlists/${id}/share`, {
        method: 'POST',
        body: JSON.stringify({ userId: shareUserId.trim(), permission: sharePermission }),
      });
      setShareOk(true);
      setShareUserId('');
    } catch {
      setShareError("Impossible d'envoyer l'invitation.");
    }
    setSharing(false);
  }

  if (loading) {
    return (
      <div className="flex flex-col gap-3">
        <div className="h-6 w-1/3 rounded bg-od-surface-hi animate-pulse" />
        {[...Array(4)].map((_, i) => (
          <div key={i} className="h-14 rounded border border-od-border bg-od-surface animate-pulse" />
        ))}
      </div>
    );
  }

  if (error === 'forbidden') {
    return (
      <div className="flex flex-col items-center gap-4 pt-16 text-center">
        <span className="font-mono text-3xl text-od-accent">⊘</span>
        <p className="text-sm text-od-muted">Accès refusé à cette playlist.</p>
        <Link to="/playlists" className="font-mono text-xs text-od-muted hover:text-od-text transition-colors">
          ← Playlists
        </Link>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="flex flex-col items-center gap-4 pt-16">
        <p className="text-sm text-od-muted">Playlist introuvable.</p>
        <Link to="/playlists" className="font-mono text-xs text-od-muted hover:text-od-text transition-colors">
          ← Playlists
        </Link>
      </div>
    );
  }

  const { playlist, videos, permission } = data;
  const isOwner = permission === 'owner';

  return (
    <div className="flex flex-col gap-6">

      {/* Header */}
      <div className="flex flex-col gap-3 border-b border-od-border pb-6">
        {editOpen ? (
          <form onSubmit={handleEdit} className="flex flex-col gap-3 rounded border border-od-border bg-od-surface p-4">
            <p className="font-mono text-xs text-od-muted uppercase tracking-widest">Modifier</p>
            <input
              value={editTitle}
              onChange={(e) => setEditTitle(e.target.value)}
              required
              className="rounded border border-od-border bg-od-bg px-3 py-2 text-sm text-od-text placeholder-od-muted outline-none focus:border-od-accent"
            />
            <select
              value={editVisibility}
              onChange={(e) => setEditVisibility(e.target.value as 'private' | 'shared' | 'public')}
              className="rounded border border-od-border bg-od-bg px-3 py-2 text-sm text-od-text outline-none focus:border-od-accent"
            >
              <option value="private">Privée</option>
              <option value="shared">Partagée</option>
              <option value="public">Publique</option>
            </select>
            <div className="flex gap-2">
              <button
                type="submit"
                disabled={saving}
                className="rounded border border-od-accent px-4 py-1.5 font-mono text-xs text-od-accent hover:bg-od-accent hover:text-od-bg transition-colors disabled:opacity-40"
              >
                {saving ? '…' : 'Enregistrer'}
              </button>
              <button
                type="button"
                onClick={() => setEditOpen(false)}
                className="rounded border border-od-border px-4 py-1.5 font-mono text-xs text-od-muted hover:text-od-text transition-colors"
              >
                Annuler
              </button>
            </div>
          </form>
        ) : (
          <>
            <div className="flex items-center gap-3">
              <h1 className="text-xl font-semibold text-od-text">{playlist.title}</h1>
              <span className="font-mono text-xs text-od-muted">{permission}</span>
            </div>
            {playlist.description && (
              <p className="text-sm text-od-muted">{playlist.description}</p>
            )}
            {isOwner && (
              <div className="flex gap-2">
                <button
                  onClick={openEdit}
                  className="rounded border border-od-border px-3 py-1 font-mono text-xs text-od-muted hover:border-od-accent hover:text-od-accent transition-colors"
                >
                  Éditer
                </button>
                <button
                  onClick={() => { setShareOpen(true); setShareError(null); setShareOk(false); }}
                  className="rounded border border-od-border px-3 py-1 font-mono text-xs text-od-muted hover:border-od-accent hover:text-od-accent transition-colors"
                >
                  Partager
                </button>
                <button
                  onClick={handleDelete}
                  className="rounded border border-od-border px-3 py-1 font-mono text-xs text-od-muted hover:border-od-crit hover:text-od-crit transition-colors"
                >
                  Supprimer
                </button>
              </div>
            )}
          </>
        )}
        {actionError && <p className="font-mono text-xs text-od-crit">{actionError}</p>}
      </div>

      {/* Share modal */}
      {shareOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-od-bg/80">
          <div className="w-full max-w-sm rounded border border-od-border bg-od-surface p-6 flex flex-col gap-4">
            <p className="font-mono text-xs text-od-muted uppercase tracking-widest">Partager</p>
            <form onSubmit={handleShare} className="flex flex-col gap-3">
              <input
                value={shareUserId}
                onChange={(e) => setShareUserId(e.target.value)}
                placeholder="ID utilisateur"
                required
                className="rounded border border-od-border bg-od-bg px-3 py-2 text-sm text-od-text placeholder-od-muted outline-none focus:border-od-accent"
              />
              <select
                value={sharePermission}
                onChange={(e) => setSharePermission(e.target.value as 'view' | 'edit')}
                className="rounded border border-od-border bg-od-bg px-3 py-2 text-sm text-od-text outline-none focus:border-od-accent"
              >
                <option value="view">Lecture seule</option>
                <option value="edit">Édition</option>
              </select>
              {shareError && <p className="font-mono text-xs text-od-crit">{shareError}</p>}
              {shareOk && <p className="font-mono text-xs text-od-ok">Invitation envoyée.</p>}
              <div className="flex gap-2">
                <button
                  type="submit"
                  disabled={sharing || !shareUserId.trim()}
                  className="rounded border border-od-accent px-4 py-1.5 font-mono text-xs text-od-accent hover:bg-od-accent hover:text-od-bg transition-colors disabled:opacity-40"
                >
                  {sharing ? '…' : 'Inviter'}
                </button>
                <button
                  type="button"
                  onClick={() => setShareOpen(false)}
                  className="rounded border border-od-border px-4 py-1.5 font-mono text-xs text-od-muted hover:text-od-text transition-colors"
                >
                  Fermer
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Videos */}
      {videos.length === 0 ? (
        <p className="text-sm text-od-muted">Aucune vidéo dans cette playlist.</p>
      ) : (
        <div className="flex flex-col gap-2">
          {videos.map((v, i) => (
            <div
              key={v.id}
              className="flex items-center gap-4 rounded border border-od-border bg-od-surface px-4 py-3"
            >
              <span className="font-mono text-xs text-od-muted w-5 shrink-0">{i + 1}</span>
              <Link
                to={`/video/${v.id}`}
                className="flex flex-1 items-center gap-4 hover:opacity-80 transition-opacity min-w-0"
              >
                {v.thumbnailUrl && (
                  <img src={v.thumbnailUrl} alt="" className="h-10 w-16 rounded object-cover shrink-0" />
                )}
                <span className="flex-1 text-sm text-od-text truncate">{v.title}</span>
                {v.duration && (
                  <span className="font-mono text-xs text-od-muted shrink-0">
                    {Math.floor(v.duration / 60)}:{String(v.duration % 60).padStart(2, '0')}
                  </span>
                )}
              </Link>
              {isOwner && (
                <button
                  onClick={() => handleRemoveVideo(v.id)}
                  className="font-mono text-xs text-od-muted hover:text-od-crit transition-colors shrink-0"
                >
                  ✕
                </button>
              )}
            </div>
          ))}
        </div>
      )}

      <Link to="/playlists" className="self-start font-mono text-xs text-od-muted hover:text-od-text transition-colors">
        ← Playlists
      </Link>

    </div>
  );
}
