// app/admin/authors/add/AddAuthor.jsx

"use client";

import { useState } from "react";
import { ArrowLeft, Save, User, Globe, Facebook, Twitter, Instagram, Linkedin, FileText } from "lucide-react";
import { useRouter } from "next/navigation";
import Swal from 'sweetalert2';

const AddAuthor = () => {
  const router = useRouter();
  
  const [formData, setFormData] = useState({
    full_name: "",
    slug: "",
    bio: "",
    profile_image: "",
    website: "",
    social_facebook: "",
    social_twitter: "",
    social_instagram: "",
    social_linkedin: "",
    status: "active"
  });

  const [loading, setLoading] = useState(false);
  const [imageUploading, setImageUploading] = useState(false);
  const [validationErrors, setValidationErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
    
    // Clear validation error for this field
    if (validationErrors[name]) {
      setValidationErrors(prev => ({
        ...prev,
        [name]: undefined
      }));
    }
  };

  const handleImageChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      setImageUploading(true);
      const formData = new FormData();
      formData.append('image', file);
      formData.append('uploadType', 'authors-profile');

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

      const data = await res.json();
      
      if (data.success && data.url) {
        setFormData(prev => ({ 
          ...prev, 
          profile_image: data.url
        }));
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: 'Profile image uploaded successfully!',
          confirmButtonColor: '#0B6D76',
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Error!',
          text: data.message || 'Image upload failed',
          confirmButtonColor: '#0B6D76',
        });
      }
    } catch (error) {
      console.error('Upload error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Image upload error',
        confirmButtonColor: '#0B6D76',
      });
    } finally {
      setImageUploading(false);
    }
  };

  const validateForm = () => {
    const errors = {};
    
    if (!formData.full_name.trim()) {
      errors.full_name = "Author name is required";
    }
    
    if (formData.slug && formData.slug.includes(' ')) {
      errors.slug = "Slug cannot contain spaces";
    }
    
    if (formData.website && !formData.website.startsWith('http://') && !formData.website.startsWith('https://')) {
      errors.website = "Website must start with http:// or https://";
    }
    
    return errors;
  };

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

    // Validate form
    const errors = validateForm();
    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        html: Object.values(errors).map(error => `<p>• ${error}</p>`).join(''),
        confirmButtonColor: '#0B6D76',
      });
      return;
    }

    try {
      setLoading(true);
      
      const res = await fetch("/api/internal/authors", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      const data = await res.json();

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

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

  return (
    <div className="p-6 bg-gradient-to-br from-blue-50 to-cyan-100 min-h-screen">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <button
          onClick={() => router.push("/admin/authors")}
          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 New Author</h1>
          <p className="text-gray-600 mt-1">Create a new author profile</p>
        </div>
      </div>

      {/* Form */}
      <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow-xl p-6 sm:p-8 max-w-4xl mx-auto">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          {/* Left Column - Basic Info & Image */}
          <div className="lg:col-span-1">
            {/* Profile Image Upload */}
            <div className="mb-6">
              <label className="block text-sm font-semibold text-gray-700 mb-2">
                Profile Image
              </label>
              <div className="border-2 border-dashed border-gray-300 rounded-xl p-4 text-center hover:border-gray-400 transition-colors">
                {formData.profile_image ? (
                  <div className="space-y-3">
                    <div className="w-32 h-32 mx-auto rounded-full overflow-hidden bg-gray-200">
                      <img 
                        src={formData.profile_image} 
                        alt="Profile preview"
                        className="w-full h-full object-cover"
                      />
                    </div>
                    <button
                      type="button"
                      onClick={() => setFormData(prev => ({ ...prev, profile_image: "" }))}
                      className="text-sm text-red-600 hover:text-red-800"
                    >
                      Remove Image
                    </button>
                  </div>
                ) : (
                  <div>
                    <User className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                    <p className="text-sm text-gray-500 mb-2">Upload profile picture</p>
                    <label className="cursor-pointer">
                      <span className="px-4 py-2 bg-[#217484] text-white rounded-lg hover:bg-[#1a5d6b] transition-colors inline-block">
                        Choose Image
                      </span>
                      <input
                        type="file"
                        accept="image/*"
                        onChange={handleImageChange}
                        className="hidden"
                        disabled={imageUploading}
                      />
                    </label>
                    <p className="text-xs text-gray-400 mt-2">JPG, PNG, GIF up to 2MB</p>
                  </div>
                )}
                {imageUploading && (
                  <div className="mt-3">
                    <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-[#217484] mx-auto"></div>
                    <p className="text-xs text-gray-500 mt-1">Uploading...</p>
                  </div>
                )}
              </div>
            </div>

            {/* Status */}
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Status</label>
              <div className="flex gap-4">
                <label className="flex items-center gap-2">
                  <input
                    type="radio"
                    name="status"
                    value="active"
                    checked={formData.status === "active"}
                    onChange={handleChange}
                    className="w-4 h-4 text-[#217484]"
                  />
                  <span className="text-gray-700">Active</span>
                </label>
                <label className="flex items-center gap-2">
                  <input
                    type="radio"
                    name="status"
                    value="inactive"
                    checked={formData.status === "inactive"}
                    onChange={handleChange}
                    className="w-4 h-4 text-gray-500"
                  />
                  <span className="text-gray-700">Inactive</span>
                </label>
              </div>
            </div>
          </div>

          {/* Right Column - Form Fields */}
          <div className="lg:col-span-2">
            {/* Basic Info */}
            <div className="mb-6">
              <h3 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                <User className="w-5 h-5" />
                Basic Information
              </h3>
              
              {/* Full Name */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Full Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  name="full_name"
                  value={formData.full_name}
                  onChange={handleChange}
                  required
                  className={`w-full px-4 py-2 border ${validationErrors.full_name ? 'border-red-300' : 'border-gray-300'} rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent`}
                  placeholder="John Doe"
                />
                {validationErrors.full_name && (
                  <p className="text-red-500 text-xs mt-1">{validationErrors.full_name}</p>
                )}
              </div>

              {/* Slug */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Slug
                </label>
                <input
                  type="text"
                  name="slug"
                  value={formData.slug}
                  onChange={handleChange}
                  className={`w-full px-4 py-2 border ${validationErrors.slug ? 'border-red-300' : 'border-gray-300'} rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent`}
                  placeholder="john-doe (auto-generated if empty)"
                />
                {validationErrors.slug && (
                  <p className="text-red-500 text-xs mt-1">{validationErrors.slug}</p>
                )}
                <p className="text-xs text-gray-500 mt-1">
                  URL-friendly identifier. Leave empty to auto-generate from name.
                </p>
              </div>

              {/* Bio */}
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Bio
                </label>
                <textarea
                  name="bio"
                  value={formData.bio}
                  onChange={handleChange}
                  rows="4"
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                  placeholder="Tell us about the author..."
                />
              </div>

              {/* Website */}
              <div className="mb-6">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Website
                </label>
                <div className="relative">
                  <Globe className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type="url"
                    name="website"
                    value={formData.website}
                    onChange={handleChange}
                    className={`w-full pl-10 pr-4 py-2 border ${validationErrors.website ? 'border-red-300' : 'border-gray-300'} rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent`}
                    placeholder="https://example.com"
                  />
                </div>
                {validationErrors.website && (
                  <p className="text-red-500 text-xs mt-1">{validationErrors.website}</p>
                )}
              </div>
            </div>

            {/* Social Media */}
            <div className="mb-6">
              <h3 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                <FileText className="w-5 h-5" />
                Social Media Links
              </h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Facebook */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    <Facebook className="w-4 h-4 inline mr-1 text-blue-600" />
                    Facebook
                  </label>
                  <div className="relative">
                    <Facebook className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="url"
                      name="social_facebook"
                      value={formData.social_facebook}
                      onChange={handleChange}
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                      placeholder="https://facebook.com/username"
                    />
                  </div>
                </div>

                {/* Twitter */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    <Twitter className="w-4 h-4 inline mr-1 text-blue-400" />
                    Twitter
                  </label>
                  <div className="relative">
                    <Twitter className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="url"
                      name="social_twitter"
                      value={formData.social_twitter}
                      onChange={handleChange}
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                      placeholder="https://twitter.com/username"
                    />
                  </div>
                </div>

                {/* Instagram */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    <Instagram className="w-4 h-4 inline mr-1 text-pink-600" />
                    Instagram
                  </label>
                  <div className="relative">
                    <Instagram className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="url"
                      name="social_instagram"
                      value={formData.social_instagram}
                      onChange={handleChange}
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                      placeholder="https://instagram.com/username"
                    />
                  </div>
                </div>

                {/* LinkedIn */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    <Linkedin className="w-4 h-4 inline mr-1 text-blue-700" />
                    LinkedIn
                  </label>
                  <div className="relative">
                    <Linkedin className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="url"
                      name="social_linkedin"
                      value={formData.social_linkedin}
                      onChange={handleChange}
                      className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#217484] focus:border-transparent"
                      placeholder="https://linkedin.com/in/username"
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* Submit Button */}
            <div className="flex justify-end mt-8 pt-6 border-t">
              <button
                type="submit"
                disabled={loading || imageUploading}
                className={`px-8 py-3 rounded-xl flex items-center gap-2 transition-all ${
                  loading || imageUploading
                    ? '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 Author...</span>
                  </>
                ) : (
                  <>
                    <Save className="w-5 h-5" />
                    <span>Add Author</span>
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>
  );
};

export default AddAuthor;