"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import SummernoteEditor from "../../../../app/components/organisms/SummernoteEditor";
import Swal from "sweetalert2";

const AddGuide = () => {
  const router = useRouter();

  const [universities, setUniversities] = useState([]);
  const [subjects, setSubjects] = useState([]);
  const [authors, setAuthors] = useState([]); // Added authors state
  const [isUploading, setIsUploading] = useState(false);
  const [uploadedImages, setUploadedImages] = useState("");
  const [title, setTitle] = useState("");
  const [type, setType] = useState("University");
  const [typeID, setTypeID] = useState("");
  const [slug, setSlug] = useState("");
  const [description, setDescription] = useState("");
  const [isActive, setIsActive] = useState(true);
  const [showMeta, setShowMeta] = useState(false);
  const [metaTitle, setMetaTitle] = useState("");
  const [metaDescription, setMetaDescription] = useState("");
  const [metaKeywords, setMetaKeywords] = useState("");
  const [authorId, setAuthorId] = useState(""); // Added authorId
  const [isloading, setIsLoading] = useState(false);

  // Function to generate slug from title
  const generateSlug = (title) => {
    return title
      .toLowerCase()
      .trim()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-')
      .replace(/^-+|-+$/g, '');
  };

  // Fetch universities, subjects, and authors on mount
  useEffect(() => {
    const fetchdata = async () => {
      try {
        const [universitiesResponse, subjectsResponse, authorsResponse] = await Promise.all([
          fetch('/api/internal/new/getuniversity', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
          }),
          fetch('/api/internal/new/getsubject', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' }
          }),
          fetch('/api/internal/authors?status=active', { // Fetch active authors
            method: 'GET',
            headers: { 'Content-Type': 'application/json' }
          })
        ]);

        if (!universitiesResponse.ok || !subjectsResponse.ok || !authorsResponse.ok) {
          throw new Error('Failed to fetch data');
        }

        const universityData = await universitiesResponse.json();
        const subjectsData = await subjectsResponse.json();
        const authorsData = await authorsResponse.json();

        setUniversities(universityData.data || []);
        setSubjects(subjectsData.data || []);
        setAuthors(authorsData.data || []);
      } catch (error) {
        console.error("Error fetching data:", error);
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: 'Failed to load data',
          confirmButtonColor: '#0B6D76'
        });
      }
    };

    fetchdata();
  }, []);

  const uploadImage = async (file, uploadType = 'guides') => {
    try {
      const formData = new FormData();
      formData.append('image', file);
      formData.append('uploadType', uploadType);

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

      if (!response.ok) {
        throw new Error('Failed to upload image');
      }

      const data = await response.json();
      return data.s3Key;
    } catch (error) {
      console.error('Error uploading image:', error);
      throw error;
    }
  };

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

    try {
      setIsUploading(true);
      const imageUrl = await uploadImage(file, 'guides');
      setUploadedImages(imageUrl);
    } catch (error) {
      Swal.fire({
        icon: 'error',
        title: 'Upload Error',
        text: error.message || 'Failed to upload image',
        confirmButtonColor: '#0B6D76'
      });
    } finally {
      setIsUploading(false);
    }
  };

  const removeImage = () => {
    setUploadedImages("");
  };

  // Handle guide type change
  const handleTypeChange = (e) => {
    const newType = e.target.value;
    setType(newType);
    setTypeID("");
  };

  const handleDescriptionChange = (content) => {
    setDescription(content);
  };

  // Handle title change and auto-generate slug
  const handleTitleChange = (e) => {
    const newTitle = e.target.value;
    setTitle(newTitle);
    setSlug(generateSlug(newTitle));
  };

  // Handle slug change manually
  const handleSlugChange = (e) => {
    setSlug(e.target.value);
  };

  const handleCheckboxChange = (e) => {
    setShowMeta(e.target.checked);
  };

  const handleActiveChange = (e) => {
    setIsActive(e.target.checked);
  };

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

    // Validate required fields
    if (!title || !slug || !typeID) {
      Swal.fire({
        icon: 'warning',
        title: 'Missing Fields',
        text: 'Please fill in all required fields',
        confirmButtonColor: '#0B6D76'
      });
      return;
    }

    try {
      setIsLoading(true);

      // Construct the payload with author_id
      const payload = {
        title,
        type,
        type_id: typeID,
        slug,
        description,
        is_active: isActive,
        show_meta: showMeta ? "on" : "off",
        meta_title: metaTitle,
        meta_description: metaDescription,
        meta_keywords: metaKeywords,
        image: uploadedImages,
        author_id: authorId || null // Include author_id
      };

      console.log("Form Payload:", payload);

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

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.message || data.details || "Failed to add guide");
      }

      Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: data.message,
        confirmButtonColor: '#10b981'
      }).then(() => {
        router.push("/admin/guide");
      });

    } catch (error) {
      console.error("Error submitting form:", error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: error.message || 'Failed to submit form',
        confirmButtonColor: '#ef4444'
      });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="p-4 sm:p-6 max-w-4xl mx-auto">
      <h1 className="text-xl sm:text-2xl font-bold mb-4">Add Guide</h1>
      <form
        onSubmit={handleSubmit}
        className="space-y-6 bg-white p-4 sm:p-6 rounded-xl shadow"
      >
        {/* Guide Type */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium">Guide Type *</label>
            <select
              name="type"
              value={type}
              onChange={handleTypeChange}
              className="w-full border px-3 py-2 rounded"
              required
            >
              <option value="University">University</option>
              <option value="Subject">Subject</option>
            </select>
          </div>
          {type === "University" && (
            <div>
              <label className="block text-sm font-medium">University *</label>
              <select
                name="university_id"
                value={typeID}
                onChange={(e) => setTypeID(e.target.value)}
                className="w-full border px-3 py-2 rounded"
                required
              >
                <option value="">Select University</option>
                {universities.map((uni) => (
                  <option key={uni.id} value={uni.id}>
                    {uni.name}
                  </option>
                ))}
              </select>
            </div>
          )}
          {type === "Subject" && (
            <div>
              <label className="block text-sm font-medium">Subject *</label>
              <select
                name="subject_id"
                value={typeID}
                onChange={(e) => setTypeID(e.target.value)}
                className="w-full border px-3 py-2 rounded"
                required
              >
                <option value="">Select Subject</option>
                {subjects.map((sub) => (
                  <option key={sub.id} value={sub.id}>
                    {sub.name}
                  </option>
                ))}
              </select>
            </div>
          )}
        </div>

        {/* Title / Slug */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium">Title *</label>
            <input
              type="text"
              name="title"
              value={title}
              onChange={handleTitleChange}
              className="w-full border px-3 py-2 rounded"
              required
              placeholder="Enter guide title"
            />
          </div>
          <div>
            <label className="block text-sm font-medium">Slug *</label>
            <input
              type="text"
              name="slug"
              value={slug}
              onChange={handleSlugChange}
              className="w-full border px-3 py-2 rounded"
              required
              placeholder="Auto-generated from title"
            />
            <p className="text-xs text-gray-500 mt-1">
              Slug is automatically generated from the title. You can edit it manually if needed.
            </p>
          </div>
        </div>

        {/* Author Field */}
        <div>
          <label className="block text-sm font-medium">Written By (Author)</label>
          <select
            name="author_id"
            value={authorId}
            onChange={(e) => setAuthorId(e.target.value)}
            className="w-full border px-3 py-2 rounded"
          >
            <option value="">Select Author (Optional)</option>
            {authors.map((author) => (
              <option key={author.id} value={author.id}>
                {author.full_name}
              </option>
            ))}
          </select>
          <p className="text-xs text-gray-500 mt-1">
            Select the author who wrote this guide
          </p>
        </div>

        {/* Summernote Description */}
        <div>
          <label className="block text-sm font-medium">Description</label>
          <SummernoteEditor
            value={description}
            onChange={handleDescriptionChange}
          />
        </div>

        {/* Featured Image */}
        <div>
          <div className="space-y-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Featured Image</label>
              <input
                type="file"
                accept="image/*"
                onChange={(e) => handleFileUpload(e, 'featured')}
                className="block w-full text-sm text-gray-500
                  file:mr-4 file:py-2 file:px-4
                  file:rounded-md file:border-0
                  file:text-sm file:font-semibold
                  file:bg-blue-50 file:text-blue-700
                  hover:file:bg-blue-100"
                disabled={isUploading}
              />
              {uploadedImages && (
                <div className="mt-2">
                  <img
                    src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${uploadedImages}`}
                    alt="Featured preview"
                    className="h-20 object-contain"
                  />
                  <button
                    type="button"
                    onClick={removeImage}
                    className="mt-1 text-red-600 text-sm"
                    disabled={isUploading}
                  >
                    Remove
                  </button>
                </div>
              )}
              {isUploading && !uploadedImages && (
                <div className="mt-2 text-sm text-gray-500">Uploading Image...</div>
              )}
            </div>
          </div>
        </div>

        {/* Meta Tags */}
        <div>
          <label className="flex items-center space-x-2 text-sm">
            <input
              type="checkbox"
              name="show_meta"
              checked={showMeta}
              onChange={handleCheckboxChange}
            />
            <span>Enable Meta Tags</span>
          </label>
        </div>
        
        {showMeta && (
          <div className="space-y-4 p-4 border rounded-lg">
            <div>
              <label className="block text-sm font-medium mb-1">Meta Title</label>
              <input
                type="text"
                name="meta_title"
                value={metaTitle}
                onChange={(e) => setMetaTitle(e.target.value)}
                placeholder="Meta Title"
                className="w-full border px-3 py-2 rounded"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Meta Description</label>
              <textarea
                name="meta_description"
                value={metaDescription}
                onChange={(e) => setMetaDescription(e.target.value)}
                placeholder="Meta Description"
                className="w-full border px-3 py-2 rounded"
                rows="3"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">Meta Keywords</label>
              <input
                type="text"
                name="meta_keywords"
                value={metaKeywords}
                onChange={(e) => setMetaKeywords(e.target.value)}
                placeholder="Meta Keywords (comma separated)"
                className="w-full border px-3 py-2 rounded"
              />
              <p className="text-xs text-gray-500 mt-1">
                Separate keywords with commas (e.g., "keyword1, keyword2, keyword3")
              </p>
            </div>
          </div>
        )}

        {/* Active Checkbox */}
        <div>
          <label className="flex items-center space-x-2 text-sm">
            <input
              type="checkbox"
              name="active"
              checked={isActive}
              onChange={handleActiveChange}
            />
            <span>Active</span>
          </label>
        </div>

        {/* Submit Button */}
        <div className="flex justify-end gap-4">
          <button
            type="button"
            onClick={() => router.push("/admin/guide")}
            className="px-6 py-2 border border-gray-300 rounded text-gray-700 hover:bg-gray-50"
            disabled={isloading}
          >
            Cancel
          </button>
          <button
            type="submit"
            className="bg-blue-600 text-white px-6 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
            disabled={isloading}
          >
            {isloading ? (
              <span className="flex items-center gap-2">
                <span className="inline-block h-4 w-4 animate-spin rounded-full border-2 border-solid border-current border-r-transparent"></span>
                Submitting...
              </span>
            ) : (
              "Submit"
            )}
          </button>
        </div>
      </form>
    </div>
  );
};

export default AddGuide;