'use client';

import React, { useState, useEffect } from 'react';
import Image from 'next/image';
import {
  Plus,
  Video,
  Copy,
  Check,
  ExternalLink,
  Users,
  AlertCircle,
  Sparkles,
} from 'lucide-react';
import { extractYouTubeId, getYouTubeThumbnailUrl } from '@/lib/youtube';

interface VideoItem {
  id: string;
  youtube_video_id: string;
  title: string;
  thumbnail_url: string;
  duration_seconds: number;
  created_at: string;
  recipientsCount: number;
}

interface GeneratedLink {
  recipientName: string;
  trackingUrl: string;
  token: string;
}

export default function AdminVideosPage() {
  const [videos, setVideos] = useState<VideoItem[]>([]);
  const [loading, setLoading] = useState(true);

  // Form states
  const [urlInput, setUrlInput] = useState('');
  const [recipientInput, setRecipientInput] = useState('');
  const [detectedVideoId, setDetectedVideoId] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Modal / newly generated links
  const [generatedLinks, setGeneratedLinks] = useState<GeneratedLink[]>([]);
  const [copiedToken, setCopiedToken] = useState<string | null>(null);

  // Quick assign modal for existing video
  const [assigningVideo, setAssigningVideo] = useState<VideoItem | null>(null);
  const [quickRecipientName, setQuickRecipientName] = useState('');
  const [assigningSubmitting, setAssigningSubmitting] = useState(false);

  const fetchVideos = async () => {
    try {
      const res = await fetch('/api/admin/videos');
      if (res.ok) {
        const data = await res.json();
        setVideos(data);
      }
    } catch (err) {
      console.error('Failed to load videos:', err);
    } finally {
      setLoading(false);
    }
  };

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

  // Update preview when URL changes
  useEffect(() => {
    const id = extractYouTubeId(urlInput);
    setDetectedVideoId(id);
  }, [urlInput]);

  const handleAddVideo = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!detectedVideoId) {
      setError('Please provide a valid YouTube URL or 11-character video ID.');
      return;
    }

    setSubmitting(true);
    setError(null);

    // Split recipient names by comma or newline if multiple
    const names = recipientInput
      .split(/[,\n]/)
      .map(n => n.trim())
      .filter(Boolean);

    try {
      const res = await fetch('/api/admin/videos', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          url: urlInput,
          recipientNames: names,
        }),
      });

      const data = await res.json();
      if (!res.ok) {
        throw new Error(data.error || 'Failed to save video');
      }

      if (data.generatedLinks && data.generatedLinks.length > 0) {
        setGeneratedLinks(data.generatedLinks);
      }

      // Reset form
      setUrlInput('');
      setRecipientInput('');
      setDetectedVideoId(null);
      fetchVideos();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Error adding video');
    } finally {
      setSubmitting(false);
    }
  };

  const handleQuickAssign = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!assigningVideo || !quickRecipientName.trim()) return;

    setAssigningSubmitting(true);
    try {
      const res = await fetch('/api/admin/assignments', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          videoId: assigningVideo.id,
          recipientName: quickRecipientName.trim(),
        }),
      });

      const data = await res.json();
      if (res.ok && data.trackingUrl) {
        setGeneratedLinks([
          {
            recipientName: quickRecipientName.trim(),
            trackingUrl: data.trackingUrl,
            token: data.token,
          },
        ]);
        setAssigningVideo(null);
        setQuickRecipientName('');
        fetchVideos();
      }
    } catch (err) {
      console.error('Failed to assign recipient:', err);
    } finally {
      setAssigningSubmitting(false);
    }
  };

  const copyToClipboard = (text: string, token: string) => {
    navigator.clipboard.writeText(text);
    setCopiedToken(token);
    setTimeout(() => setCopiedToken(null), 2500);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-2xl font-bold text-slate-900 tracking-tight">Videos & Assignments</h1>
        <p className="text-xs text-slate-500 mt-1">
          Add YouTube videos, create recipient assignments, and generate individual tracking links.
        </p>
      </div>

      {/* Generated Links Success Alert */}
      {generatedLinks.length > 0 && (
        <div className="bg-emerald-50 border border-emerald-200 rounded-xl p-5 shadow-sm">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center space-x-2 text-emerald-800">
              <Sparkles className="w-5 h-5 text-emerald-600" />
              <h3 className="text-sm font-bold">Tracking Links Generated Successfully!</h3>
            </div>
            <button
              onClick={() => setGeneratedLinks([])}
              className="text-xs text-emerald-700 hover:text-emerald-900 font-semibold"
            >
              Dismiss
            </button>
          </div>
          <p className="text-xs text-emerald-700 mb-3">
            Send each unique link to its respective recipient. Each link records watch duration independently.
          </p>

          <div className="space-y-2">
            {generatedLinks.map((item, idx) => (
              <div
                key={idx}
                className="bg-white rounded-lg border border-emerald-200 p-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2"
              >
                <div>
                  <div className="text-xs font-bold text-slate-900">{item.recipientName}</div>
                  <div className="text-xs text-slate-500 font-mono break-all">{item.trackingUrl}</div>
                </div>
                <div className="flex items-center space-x-2">
                  <button
                    onClick={() => copyToClipboard(item.trackingUrl, item.token)}
                    className="inline-flex items-center space-x-1.5 px-3 py-1.5 bg-blue-50 text-blue-700 hover:bg-blue-100 rounded text-xs font-semibold transition"
                  >
                    {copiedToken === item.token ? (
                      <>
                        <Check className="w-3.5 h-3.5 text-emerald-600" />
                        <span className="text-emerald-700">Copied!</span>
                      </>
                    ) : (
                      <>
                        <Copy className="w-3.5 h-3.5" />
                        <span>Copy Link</span>
                      </>
                    )}
                  </button>
                  <a
                    href={item.trackingUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="p-1.5 text-slate-400 hover:text-slate-700 rounded hover:bg-slate-100"
                    title="Open recipient view"
                  >
                    <ExternalLink className="w-4 h-4" />
                  </a>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Add Video Form Card */}
      <div className="bg-white rounded-xl border border-slate-200 p-5 shadow-sm">
        <h2 className="text-sm font-bold text-slate-900 mb-1 flex items-center space-x-2">
          <Plus className="w-4 h-4 text-blue-600" />
          <span>Add New YouTube Video</span>
        </h2>
        <p className="text-xs text-slate-500 mb-4">
          Paste a YouTube URL and optionally enter recipient name(s) to generate tracking links immediately.
        </p>

        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 text-xs rounded-lg flex items-center space-x-2">
            <AlertCircle className="w-4 h-4 flex-shrink-0" />
            <span>{error}</span>
          </div>
        )}

        <form onSubmit={handleAddVideo} className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Left: Input fields */}
            <div className="space-y-3">
              <div>
                <label className="block text-xs font-semibold text-slate-700 mb-1">
                  YouTube Video URL or ID
                </label>
                <input
                  type="text"
                  required
                  placeholder="https://www.youtube.com/watch?v=..."
                  value={urlInput}
                  onChange={(e) => setUrlInput(e.target.value)}
                  className="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
                <span className="text-[10px] text-slate-400 mt-1 block">
                  Supports standard watch links, youtu.be, shorts, and embeds
                </span>
              </div>

              <div>
                <label className="block text-xs font-semibold text-slate-700 mb-1">
                  Recipient Name(s) <span className="font-normal text-slate-400">(Optional)</span>
                </label>
                <input
                  type="text"
                  placeholder="e.g. Alice Smith, Bob Jones (comma separated)"
                  value={recipientInput}
                  onChange={(e) => setRecipientInput(e.target.value)}
                  className="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
                <span className="text-[10px] text-slate-400 mt-1 block">
                  Generates an individual tracking link for each recipient specified
                </span>
              </div>
            </div>

            {/* Right: Detected Video Preview */}
            <div className="border border-slate-200 rounded-lg p-3 bg-slate-50 flex flex-col justify-center items-center text-center">
              {detectedVideoId ? (
                <div className="w-full">
                  <div className="relative aspect-video w-full rounded-md overflow-hidden bg-black mb-2 shadow-sm">
                    {/* Next.js Image with unoptimized fallback */}
                    <img
                      src={getYouTubeThumbnailUrl(detectedVideoId)}
                      alt="YouTube Thumbnail"
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div className="text-xs font-semibold text-slate-800">
                    YouTube ID: <span className="font-mono text-blue-600">{detectedVideoId}</span>
                  </div>
                </div>
              ) : (
                <div className="text-slate-400 p-4">
                  <Video className="w-8 h-8 mx-auto mb-1 opacity-50" />
                  <p className="text-xs">Paste a YouTube link above to preview video</p>
                </div>
              )}
            </div>
          </div>

          <div className="flex justify-end pt-2">
            <button
              type="submit"
              disabled={submitting || !detectedVideoId}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white rounded-lg text-xs font-semibold transition shadow-sm"
            >
              {submitting ? 'Adding Video...' : 'Add Video & Generate Links'}
            </button>
          </div>
        </form>
      </div>

      {/* Videos List */}
      <div className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
        <div className="p-4 sm:px-6 border-b border-slate-100 flex items-center justify-between">
          <h2 className="text-sm font-bold text-slate-900">All Portal Videos ({videos.length})</h2>
        </div>

        {loading ? (
          <div className="p-8 text-center text-xs text-slate-400">Loading videos...</div>
        ) : videos.length === 0 ? (
          <div className="p-8 text-center text-xs text-slate-400">
            No videos added yet. Add a video above to get started.
          </div>
        ) : (
          <div className="divide-y divide-slate-100">
            {videos.map((vid) => (
              <div
                key={vid.id}
                className="p-4 sm:px-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4 hover:bg-slate-50/70 transition"
              >
                <div className="flex items-start space-x-3.5">
                  <div className="relative w-24 h-14 rounded-md overflow-hidden bg-slate-900 flex-shrink-0">
                    <img
                      src={vid.thumbnail_url || getYouTubeThumbnailUrl(vid.youtube_video_id)}
                      alt={vid.title}
                      className="w-full h-full object-cover"
                    />
                  </div>
                  <div>
                    <h3 className="text-xs sm:text-sm font-bold text-slate-900 line-clamp-1">
                      {vid.title}
                    </h3>
                    <div className="flex items-center space-x-3 text-[11px] text-slate-500 mt-1">
                      <span>
                        ID: <span className="font-mono text-slate-700">{vid.youtube_video_id}</span>
                      </span>
                      <span>&bull;</span>
                      <span className="flex items-center space-x-1">
                        <Users className="w-3 h-3 text-slate-400" />
                        <span>{vid.recipientsCount} recipient(s)</span>
                      </span>
                    </div>
                  </div>
                </div>

                <div className="flex items-center space-x-2 self-end sm:self-center">
                  <button
                    onClick={() => setAssigningVideo(vid)}
                    className="inline-flex items-center space-x-1 px-3 py-1.5 text-xs font-semibold text-blue-700 bg-blue-50 hover:bg-blue-100 rounded-lg transition"
                  >
                    <Plus className="w-3.5 h-3.5" />
                    <span>Assign Recipient</span>
                  </button>
                  <a
                    href={`https://www.youtube.com/watch?v=${vid.youtube_video_id}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="p-1.5 text-slate-400 hover:text-slate-700 rounded hover:bg-slate-100"
                    title="View on YouTube"
                  >
                    <ExternalLink className="w-4 h-4" />
                  </a>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Quick Assign Recipient Modal */}
      {assigningVideo && (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4">
          <div className="bg-white rounded-xl shadow-xl max-w-md w-full p-6 border border-slate-200">
            <h3 className="text-sm font-bold text-slate-900 mb-1">
              Assign Recipient to Video
            </h3>
            <p className="text-xs text-slate-500 mb-4 line-clamp-1">
              Video: {assigningVideo.title}
            </p>

            <form onSubmit={handleQuickAssign} className="space-y-4">
              <div>
                <label className="block text-xs font-semibold text-slate-700 mb-1">
                  Recipient Name
                </label>
                <input
                  type="text"
                  required
                  autoFocus
                  placeholder="e.g. Charlie Brown"
                  value={quickRecipientName}
                  onChange={(e) => setQuickRecipientName(e.target.value)}
                  className="w-full text-xs px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div className="flex items-center justify-end space-x-2 pt-2">
                <button
                  type="button"
                  onClick={() => setAssigningVideo(null)}
                  className="px-3 py-1.5 text-xs font-semibold text-slate-600 hover:bg-slate-100 rounded-lg"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={assigningSubmitting || !quickRecipientName.trim()}
                  className="px-4 py-1.5 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 rounded-lg transition"
                >
                  {assigningSubmitting ? 'Generating...' : 'Generate Unique Link'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
