"use client";

import { useState, useEffect } from "react";
import { Plus, Edit, Trash2, X, Check, XCircle, Upload, Image as ImageIcon } from "lucide-react";
import Pagination from "../../components/Pagination";
import Swal from 'sweetalert2';
import Image from "next/image";

const SubjectList = () => {
  const [subjects, setSubjects] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [newSubjectName, setNewSubjectName] = useState("");
  const [editSubjectId, setEditSubjectId] = useState(null);
  const [editSubjectName, setEditSubjectName] = useState("");
  const [editSubjectIcon, setEditSubjectIcon] = useState("");
  const [searchTerm, setSearchTerm] = useState("");
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);

  // Image upload states
  const [uploading, setUploading] = useState(false);
  const [imagePreview, setImagePreview] = useState(null);
  const [imageFile, setImageFile] = useState(null);
  const [editImagePreview, setEditImagePreview] = useState(null);
  const [editImageFile, setEditImageFile] = useState(null);

  // Fetch subjects when page changes or applied search term changes
  useEffect(() => {
    fetchSubjects();
  }, [currentPage, appliedSearchTerm]);

  // Fetch subjects
  const fetchSubjects = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });
      
      if (appliedSearchTerm) {
        params.append('search', appliedSearchTerm);
      }

      console.log('🔍 Fetching subjects with params:', {
        page: currentPage,
        limit: itemsPerPage,
        search: appliedSearchTerm
      });

      const res = await fetch(`/api/internal/subject?${params.toString()}`);
      if (!res.ok) throw new Error("Failed to fetch");
      const data = await res.json();
      
      console.log('📦 API Response:', {
        success: data.success,
        dataCount: data.data?.length,
        meta: data.meta
      });

      if (data.success) {
        setSubjects(data.data || []);
        setTotalItems(data.meta?.totalItems || 0);
        setTotalPages(data.meta?.totalPages || 1);
      } else {
        // Fallback for different response formats
        const subjectsArray = Array.isArray(data) ? data : data.data || [];
        setSubjects(subjectsArray);
        setTotalItems(subjectsArray.length);
        setTotalPages(Math.ceil(subjectsArray.length / itemsPerPage));
      }
    } catch (error) {
      console.error('Error fetching subjects:', error);
      setSubjects([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  };

  // Image upload handler
  const handleImageUpload = async (file) => {
    if (!file) return null;

    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('image', file);
      formData.append('uploadType', 'subject');

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

      if (!response.ok) {
        throw new Error('Upload failed');
      }

      const data = await response.json();
      return data.s3Key;
    } catch (error) {
      console.error('Upload error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Upload Failed',
        text: 'Failed to upload image. Please try again.',
      });
      return null;
    } finally {
      setUploading(false);
    }
  };

  const handleImageChange = (e, isEdit = false) => {
    const file = e.target.files[0];
    if (file) {
      // Validate file type
      if (!file.type.startsWith('image/')) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid File',
          text: 'Please select an image file.',
        });
        return;
      }

      // Validate file size (max 5MB)
      if (file.size > 5 * 1024 * 1024) {
        Swal.fire({
          icon: 'error',
          title: 'File Too Large',
          text: 'Please select an image smaller than 5MB.',
        });
        return;
      }

      if (isEdit) {
        setEditImageFile(file);
      } else {
        setImageFile(file);
      }
      
      // Create preview
      const reader = new FileReader();
      reader.onload = (e) => {
        if (isEdit) {
          setEditImagePreview(e.target.result);
        } else {
          setImagePreview(e.target.result);
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const removeImage = (isEdit = false) => {
    if (isEdit) {
      setEditImageFile(null);
      setEditImagePreview(null);
      setEditSubjectIcon("");
    } else {
      setImageFile(null);
      setImagePreview(null);
    }
  };

  // Add subject
  const handleAddSubject = async () => {
    const name = newSubjectName.trim();
    if (!name) {
      Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        text: 'Subject name is required',
      });
      return;
    }

    try {
      // Upload image if selected
      let iconKey = null;
      if (imageFile) {
        iconKey = await handleImageUpload(imageFile);
        if (!iconKey) {
          throw new Error('Failed to upload image');
        }
      }

      const res = await fetch("/api/internal/subject", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, icon: iconKey }),
      });
      
      const json = await res.json();
      
      if (!res.ok) {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: json.error || "Failed to add subject",
        });
        return;
      }

      // Refresh list to ensure we show the latest added item
      await fetchSubjects();
      setNewSubjectName("");
      setImageFile(null);
      setImagePreview(null);
      setIsModalOpen(false);
      
      Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'Subject added successfully',
      });
    } catch (error) {
      console.error(error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: "Error adding subject",
      });
    }
  };

  // Delete subject
  const handleDelete = async (id) => {
    const result = await Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!'
    });

    if (!result.isConfirmed) return;

    try {
      const res = await fetch(`/api/internal/subject/${id}`, {
        method: "DELETE",
      });
      if (!res.ok) throw new Error("Failed to delete subject");
      
      // Refresh the current page data
      fetchSubjects();
      
      Swal.fire({
        icon: 'success',
        title: 'Deleted!',
        text: 'Subject has been deleted.',
      });
    } catch (error) {
      console.error(error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: "Error deleting subject",
      });
    }
  };

  // Edit functions
  const startEdit = (subject) => {
    setEditSubjectId(subject.id);
    setEditSubjectName(subject.name);
    setEditSubjectIcon(subject.icon || "");
    setEditImagePreview(subject.icon ? `/api/internal/upload?key=${subject.icon}` : null);
    setEditImageFile(null);
  };

  const cancelEdit = () => {
    setEditSubjectId(null);
    setEditSubjectName("");
    setEditSubjectIcon("");
    setEditImagePreview(null);
    setEditImageFile(null);
  };

  const saveEdit = async (id) => {
    const name = editSubjectName.trim();
    if (!name) {
      Swal.fire({
        icon: 'error',
        title: 'Validation Error',
        text: "Subject name cannot be empty",
      });
      return;
    }

    try {
      // Upload new image if selected
      let iconKey = editSubjectIcon;
      if (editImageFile) {
        const uploadedKey = await handleImageUpload(editImageFile);
        if (uploadedKey) {
          iconKey = uploadedKey;
        } else {
          throw new Error('Failed to upload image');
        }
      }

      const res = await fetch(`/api/internal/subject/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, icon: iconKey }),
      });
      
      if (!res.ok) throw new Error("Failed to update subject");

      // Refresh the current page data
      fetchSubjects();
      cancelEdit();
      
      Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: 'Subject updated successfully',
      });
    } catch (error) {
      console.error(error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: "Error updating subject",
      });
    }
  };

  // Handle search button click
  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setCurrentPage(1);
  };

  // Clear search
  const clearSearch = () => {
    setSearchTerm("");
    setAppliedSearchTerm("");
    setCurrentPage(1);
  };

  // Handle Enter key in search
  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  const startIndex = totalItems > 0 ? (currentPage - 1) * itemsPerPage : 0;
  const endIndex = Math.min(currentPage * itemsPerPage, totalItems);

  return (
    <div className="p-6 bg-gradient-to-br from-green-50 to-teal-100 min-h-screen">
      <div className="bg-white rounded-2xl shadow-xl p-6 sm:p-8">
        {/* Header */}
        <div className="flex flex-col sm:flex-row justify-between sm:items-center gap-4 mb-6 sm:mb-8">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-800 mb-1">Subjects</h1>
            <p className="text-gray-600 text-sm sm:text-base">Manage subject records</p>
          </div>
          <button
            onClick={() => setIsModalOpen(true)}
            className="bg-green-600 text-white px-6 py-3 rounded-xl hover:bg-green-700 transition-colors flex items-center gap-2"
          >
            <Plus className="w-5 h-5" />
            Add Subject
          </button>
        </div>

        {/* Search */}
        <div className="flex items-center gap-3 mb-4 sm:mb-6">
          <div className="flex-1 flex items-center gap-2">
            <input
              type="text"
              placeholder="Search subjects..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyPress={handleKeyPress}
              className="flex-1 px-4 sm:px-5 py-2 sm:py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent text-sm sm:text-base"
            />
            <button
              onClick={handleSearch}
              className="px-6 py-2 sm:py-3 bg-green-600 text-white rounded-xl hover:bg-green-700 transition-colors flex items-center gap-2"
            >
              🔍 Search
            </button>
            {appliedSearchTerm && (
              <button
                onClick={clearSearch}
                className="px-4 py-2 sm:py-3 bg-gray-500 text-white rounded-xl hover:bg-gray-600 transition-colors"
              >
                Clear
              </button>
            )}
          </div>
          
          {/* Active Search Display */}
          {appliedSearchTerm && (
            <div className="text-sm text-gray-600 bg-green-100 px-3 py-2 rounded-lg">
              <span className="font-medium">Active search:</span> "{appliedSearchTerm}"
              <span className="ml-2 text-xs text-gray-500">
                (Found {totalItems} results)
              </span>
            </div>
          )}
        </div>

        <div className="overflow-x-auto">
          <table className="w-full min-w-[600px]">
            <thead>
              <tr className="bg-gray-100">
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600 rounded-l-xl">Icon</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-600">Subject Name</th>
                <th className="py-3 px-4 text-center text-sm font-semibold text-gray-600 rounded-r-xl">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {loading ? (
                <tr>
                  <td colSpan="3" className="py-8 text-center text-gray-500">
                    <div className="flex justify-center">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-green-600"></div>
                    </div>
                    <p className="mt-2">Loading subjects...</p>
                  </td>
                </tr>
              ) : subjects.length === 0 ? (
                <tr>
                  <td colSpan="3" className="py-8 text-center text-gray-500">
                    {appliedSearchTerm ? `No subjects found matching "${appliedSearchTerm}".` : 'No subjects found.'}
                  </td>
                </tr>
              ) : (
                subjects.map((subject) => (
                  <tr key={subject.id} className="hover:bg-gray-50 transition-colors">
                    <td className="py-3 px-4">
                      {subject.icon ? (
                        <Image 
                          src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${subject.icon}`}
                          alt={subject.name}
                          width={40}
                          height={40}
                          className="w-8 h-8 object-contain"
                          onError={(e) => {
                            e.target.src = '/placeholder-image.png';
                          }}
                        />
                      ) : (
                        <div className="w-8 h-8 bg-gray-200 rounded flex items-center justify-center">
                          <ImageIcon className="w-4 h-4 text-gray-400" />
                        </div>
                      )}
                    </td>
                    <td className="py-3 px-4">
                      {editSubjectId === subject.id ? (
                        <div className="space-y-3">
                          <input
                            type="text"
                            value={editSubjectName}
                            onChange={(e) => setEditSubjectName(e.target.value)}
                            className="w-full border px-3 py-2 rounded"
                            autoFocus
                          />
                          {/* Edit Image Upload */}
                          <div className="space-y-2">
                            <label className="block text-sm font-medium text-gray-700">
                              Change Icon
                            </label>
                            <div className="flex items-center gap-3">
                              {(editImagePreview || editSubjectIcon) && (
                                <div className="relative">
                                  <Image 
                                    src={editImagePreview || `/api/internal/upload?key=${editSubjectIcon}`}
                                    alt="Preview"
                                    width={48}
                                    height={48}
                                    className="w-12 h-12 object-contain border rounded"
                                  />
                                  <button
                                    type="button"
                                    onClick={() => removeImage(true)}
                                    className="absolute -top-1 -right-1 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
                                  >
                                    <X className="w-2 h-2" />
                                  </button>
                                </div>
                              )}
                              <div>
                                <input
                                  type="file"
                                  id={`edit-image-${subject.id}`}
                                  accept="image/*"
                                  onChange={(e) => handleImageChange(e, true)}
                                  className="hidden"
                                />
                                <label
                                  htmlFor={`edit-image-${subject.id}`}
                                  className="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm hover:bg-gray-200 transition-colors cursor-pointer flex items-center gap-1"
                                >
                                  <Upload className="w-3 h-3" />
                                  {editImagePreview || editSubjectIcon ? 'Change' : 'Upload'}
                                </label>
                              </div>
                            </div>
                          </div>
                        </div>
                      ) : (
                        <span className="font-medium text-gray-800">{subject.name}</span>
                      )}
                    </td>
                    <td className="py-3 px-4 text-center">
                      {editSubjectId === subject.id ? (
                        <div className="flex justify-center gap-2">
                          <button
                            onClick={() => saveEdit(subject.id)}
                            className="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                            title="Save"
                            disabled={uploading}
                          >
                            <Check className="w-4 h-4" />
                          </button>
                          <button
                            onClick={cancelEdit}
                            className="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                            title="Cancel"
                            disabled={uploading}
                          >
                            <XCircle className="w-4 h-4" />
                          </button>
                        </div>
                      ) : (
                        <div className="flex justify-center gap-2">
                          <button
                            onClick={() => startEdit(subject)}
                            className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                            title="Edit"
                          >
                            <Edit className="w-4 h-4" />
                          </button>
                          <button
                            onClick={() => handleDelete(subject.id)}
                            className="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                            title="Delete"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="mt-6">
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
              totalItems={totalItems}
              startIndex={startIndex}
              endIndex={endIndex}
            />
          </div>
        )}
      </div>

      {/* Add Subject Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-xl p-6 w-full max-w-md relative">
            <button
              onClick={() => setIsModalOpen(false)}
              className="absolute top-4 right-4 text-gray-500 hover:text-gray-700"
              disabled={uploading}
            >
              <X className="w-5 h-5" />
            </button>
            
            <h2 className="text-lg font-semibold mb-4">Add New Subject</h2>
            
            <div className="space-y-4">
              {/* Image Upload Section */}
              <div>
                <label className="block text-sm font-medium mb-2">Subject Icon</label>
                <div className="space-y-3">
                  {/* Image Preview */}
                  {imagePreview && (
                    <div className="relative inline-block">
                      <Image 
                        src={imagePreview} 
                        alt="Preview" 
                        width={80}
                        height={80}
                        className="w-20 h-20 object-contain border rounded-lg"
                      />
                      <button
                        type="button"
                        onClick={() => removeImage(false)}
                        className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
                        disabled={uploading}
                      >
                        <X className="w-3 h-3" />
                      </button>
                    </div>
                  )}
                  
                  {/* Upload Button */}
                  <div>
                    <input
                      type="file"
                      id="icon-upload"
                      accept="image/*"
                      onChange={(e) => handleImageChange(e, false)}
                      className="hidden"
                      disabled={uploading}
                    />
                    <label
                      htmlFor="icon-upload"
                      className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <Upload className="w-4 h-4" />
                      {uploading ? 'Uploading...' : imagePreview ? 'Change Image' : 'Upload Icon'}
                    </label>
                    <p className="text-xs text-gray-500 mt-1">
                      Supported formats: JPG, PNG, SVG, etc. Max size: 5MB
                    </p>
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">Subject Name</label>
                <input
                  type="text"
                  value={newSubjectName}
                  onChange={(e) => setNewSubjectName(e.target.value)}
                  placeholder="Enter subject name"
                  className="w-full border px-3 py-2 rounded"
                  onKeyPress={(e) => e.key === 'Enter' && handleAddSubject()}
                  disabled={uploading}
                />
              </div>
            </div>
            
            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => setIsModalOpen(false)}
                className="px-4 py-2 border rounded hover:bg-gray-100 disabled:opacity-50"
                disabled={uploading}
              >
                Cancel
              </button>
              <button
                onClick={handleAddSubject}
                className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50 flex items-center gap-2"
                disabled={uploading}
              >
                {uploading ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                    Uploading...
                  </>
                ) : (
                  'Add Subject'
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default SubjectList;