"use client";

import { useState, useEffect } from "react";
import { ArrowLeft, Save, Video, Eye, Clock, Star, Globe } from "lucide-react";
import { useRouter } from "next/navigation";
import Swal from 'sweetalert2';

const AddYouTubeVideo = () => {
  const router = useRouter();
  
  const [formData, setFormData] = useState({
    title: "",
    description: "",
    thumbnail: "",
    video_id: "",
    url: "",
    published_at: "",
    view_count: "0",
    duration: "",
    is_active: true,
    featured: false,
    country_id: "" // New field for country
  });

  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [countries, setCountries] = useState([]);
  const [countriesLoading, setCountriesLoading] = useState(false);

  // Fetch countries on component mount
  useEffect(() => {
    fetchCountries();
  }, []);

  const fetchCountries = async () => {
    try {
      setCountriesLoading(true);
      const response = await fetch(`/api/internal/countries?limit=100`);
      const result = await response.json();
      
      if (result.success) {
        setCountries(result.data);
      } else {
        console.error("Failed to fetch countries:", result.error);
      }
    } catch (error) {
      console.error("Error fetching countries:", error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Failed to load countries',
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setCountriesLoading(false);
    }
  };

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleCheckboxChange = (e) => {
    const { name, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: checked
    }));
  };

  // Extract video ID from URL when URL changes
  useEffect(() => {
    if (formData.url) {
      const videoId = extractVideoId(formData.url);
      if (videoId) {
        setFormData(prev => ({
          ...prev,
          video_id: videoId
        }));
      }
    }
  }, [formData.url]);

  const extractVideoId = (url) => {
    const match = url.match(/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/);
    return match ? match[1] : '';
  };

  const handleImageChange = async (e) => {
    const file = e.target.files?.[0];
    if (file) {
      if (file.size > 2 * 1024 * 1024) {
        Swal.fire({
          icon: 'warning',
          title: 'File Too Large',
          text: 'Image size should be less than 2MB.',
          confirmButtonColor: '#0B6D76',
        });
        return;
      }

      if (!file.type.startsWith('image/')) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid File',
          text: 'Please select an image file.',
          confirmButtonColor: '#0B6D76',
        });
        return;
      }

      try {
        setUploading(true);
        const uploadFormData = new FormData();
        uploadFormData.append('image', file);
        uploadFormData.append('uploadType', 'youtube-videos');

        const uploadResponse = await fetch('/api/internal/upload', {
          method: 'POST',
          body: uploadFormData,
        });

        const uploadResult = await uploadResponse.json();

        if (!uploadResponse.ok) {
          throw new Error(uploadResult.message || 'Upload failed');
        }

        setFormData(prev => ({ ...prev, thumbnail: uploadResult.s3Key }));
        
        Swal.fire({
          icon: 'success',
          title: 'Thumbnail Uploaded!',
          text: 'Thumbnail has been uploaded successfully.',
          confirmButtonColor: '#0B6D76',
          timer: 2000,
          showConfirmButton: false
        });
      } catch (error) {
        console.error('Upload error:', error);
        Swal.fire({
          icon: 'error',
          title: 'Upload Failed',
          text: `Upload failed: ${error.message}`,
          confirmButtonColor: '#0B6D76',
        });
      } finally {
        setUploading(false);
      }
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (loading) return;

    // Validation
    if (!formData.title || !formData.video_id || !formData.url || !formData.published_at) {
      Swal.fire({
        icon: 'error',
        title: 'Missing Fields',
        text: 'Please fill in all required fields.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    // Validate YouTube URL
    if (!formData.url.includes('youtube.com') && !formData.url.includes('youtu.be')) {
      Swal.fire({
        icon: 'error',
        title: 'Invalid URL',
        text: 'Please enter a valid YouTube URL.',
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    try {
      setLoading(true);
      
      const submitData = {
        ...formData,
        view_count: formData.view_count || "0",
        is_active: formData.is_active ? 1 : 0,
        featured: formData.featured ? 1 : 0,
        country_id: formData.country_id || null // Send null if no country selected
      };

      const res = await fetch("/api/internal/youtube-videos", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(submitData),
      });

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || "Failed to add video");
      }

      await Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'YouTube video added successfully!',
        confirmButtonColor: '#0B6D76',
      });
      
      router.push("/admin/youtube");
    } catch (err) {
      console.error("Submit Error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: err.message || "Something went wrong.",
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setLoading(false);
    }
  };

  const removeImage = () => {
    setFormData(prev => ({ ...prev, thumbnail: "" }));
  };

  const getSelectedCountryName = () => {
    if (!formData.country_id) return "";
    const country = countries.find(c => c.id === parseInt(formData.country_id));
    return country ? `${country.country} (${country.code})` : "";
  };

  return (
    <div className="p-6 bg-gradient-to-br from-purple-50 to-blue-100 min-h-screen">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={() => router.push("/admin/youtube")}
          className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
        >
          <ArrowLeft className="w-6 h-6 text-gray-600" />
        </button>
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">Add YouTube Video</h1>
          <p className="text-gray-600 mt-1">Add a new YouTube video to your collection</p>
        </div>
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow-xl p-6 sm:p-8 max-w-4xl mx-auto">
        {/* Row 1: Title and URL */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Video Title <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              name="title"
              value={formData.title}
              onChange={handleInputChange}
              required
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              placeholder="Enter video title"
            />
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              YouTube URL <span className="text-red-500">*</span>
            </label>
            <input
              type="url"
              name="url"
              value={formData.url}
              onChange={handleInputChange}
              required
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              placeholder="https://www.youtube.com/watch?v=..."
            />
            {formData.video_id && (
              <p className="text-xs text-green-600 mt-1">
                ✅ Video ID detected: {formData.video_id}
              </p>
            )}
          </div>
        </div>

        {/* Row 2: Video ID and Published Date */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Video ID <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              name="video_id"
              value={formData.video_id}
              onChange={handleInputChange}
              required
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent bg-gray-50"
              placeholder="YouTube video ID"
            />
            <p className="text-xs text-gray-500 mt-1">Auto-extracted from URL</p>
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Published Date <span className="text-red-500">*</span>
            </label>
            <div className="relative">
              <input
                type="date"
                name="published_at"
                value={formData.published_at}
                onChange={handleInputChange}
                required
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              />
            </div>
          </div>
        </div>

        {/* Row 3: View Count and Duration */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              <div className="flex items-center gap-2">
                <Eye className="w-4 h-4" />
                View Count
              </div>
            </label>
            <input
              type="text"
              name="view_count"
              value={formData.view_count}
              onChange={handleInputChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              placeholder="e.g., 1.5K, 10M, 100000"
            />
          </div>

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              <div className="flex items-center gap-2">
                <Clock className="w-4 h-4" />
                Duration
              </div>
            </label>
            <input
              type="text"
              name="duration"
              value={formData.duration}
              onChange={handleInputChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              placeholder="e.g., 10:30, 5:15"
            />
          </div>
        </div>

        {/* Row 4: Country Selection */}
        <div className="mb-6">
          <label className="block text-sm font-semibold text-gray-700 mb-2">
            <div className="flex items-center gap-2">
              <Globe className="w-4 h-4" />
              Country
            </div>
          </label>
          <div className="space-y-2">
            {countriesLoading ? (
              <div className="text-center py-4">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#217484] mx-auto"></div>
                <p className="text-sm text-gray-600 mt-2">Loading countries...</p>
              </div>
            ) : (
              <select
                name="country_id"
                value={formData.country_id}
                onChange={handleInputChange}
                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
              >
                <option value="">Select a country (optional)</option>
                {countries.map((country) => (
                  <option key={country.id} value={country.id}>
                    {country.country} ({country.code})
                  </option>
                ))}
              </select>
            )}
            
            {formData.country_id && (
              <p className="text-xs text-green-600">
                ✅ Selected: {getSelectedCountryName()}
              </p>
            )}
          </div>
        </div>

        {/* Row 5: Description */}
        <div className="mb-6">
          <label className="block text-sm font-semibold text-gray-700 mb-2">Description</label>
          <textarea
            name="description"
            value={formData.description}
            onChange={handleInputChange}
            rows={4}
            className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#217484] focus:border-transparent"
            placeholder="Enter video description..."
          />
        </div>

        {/* Row 6: Thumbnail Upload */}
        <div className="mb-6">
          <label className="block text-sm font-semibold text-gray-700 mb-2">Custom Thumbnail</label>
          <div className="border-2 border-dashed border-gray-300 rounded-xl p-6 text-center hover:border-gray-400 transition-colors">
            {uploading ? (
              <div className="text-center">
                <div className="animate-spin rounded-full h-10 w-10 border-b-2 border-[#217484] mx-auto mb-2"></div>
                <p className="text-sm text-gray-600">Uploading thumbnail...</p>
              </div>
            ) : formData.thumbnail ? (
              <div>
                <div className="w-24 h-16 bg-gradient-to-br from-red-100 to-red-200 rounded-lg mx-auto mb-2 flex items-center justify-center">
                  <Video className="w-6 h-6 text-red-400" />
                </div>
                <p className="text-xs text-green-600 mb-2">✓ Thumbnail uploaded successfully</p>
                <button
                  type="button"
                  onClick={removeImage}
                  className="text-xs text-red-600 hover:text-red-800"
                >
                  Remove Thumbnail
                </button>
              </div>
            ) : (
              <>
                <Video className="w-10 h-10 text-gray-400 mx-auto mb-2" />
                <p className="text-sm text-gray-600 mb-2">Upload custom thumbnail (optional)</p>
              </>
            )}
            <input
              type="file"
              accept="image/*"
              onChange={handleImageChange}
              className="mt-2 text-sm mx-auto"
              disabled={uploading}
            />
            {!uploading && !formData.thumbnail && (
              <p className="text-xs text-gray-500 mt-2">YouTube thumbnail will be used if not provided</p>
            )}
          </div>
        </div>

        {/* Row 7: Checkboxes */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              name="is_active"
              id="is_active"
              checked={formData.is_active}
              onChange={handleCheckboxChange}
              className="w-4 h-4 text-[#217484] rounded focus:ring-[#217484]"
            />
            <label htmlFor="is_active" className="text-sm font-medium text-gray-700">
              Active Video
            </label>
          </div>

          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              name="featured"
              id="featured"
              checked={formData.featured}
              onChange={handleCheckboxChange}
              className="w-4 h-4 text-yellow-500 rounded focus:ring-yellow-500"
            />
            <label htmlFor="featured" className="text-sm font-medium text-gray-700 flex items-center gap-2">
              <Star className="w-4 h-4 text-yellow-500" />
              Featured Video
            </label>
          </div>
        </div>

        {/* Submit Button */}
        <div className="flex justify-end mt-8 pt-6 border-t">
          <button
            type="submit"
            disabled={loading || uploading}
            className={`px-8 py-3 rounded-xl flex items-center gap-2 transition-all ${
              loading || uploading
                ? 'bg-gray-400 cursor-not-allowed'
                : 'bg-[#217484] text-white hover:bg-[#1a5d6b] hover:shadow-xl'
            }`}
          >
            {loading ? (
              <>
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                <span>Adding Video...</span>
              </>
            ) : (
              <>
                <Save className="w-5 h-5" />
                <span>Add Video</span>
              </>
            )}
          </button>
        </div>
      </form>
    </div>
  );
};

export default AddYouTubeVideo;