"use client";

import React, { useState, useEffect } from "react";
import { Plus, Edit, Trash2, X, Save, Upload, XCircle } from "lucide-react";
import { useRouter } from "next/navigation";
import Pagination from '../../components/Pagination';
import Swal from 'sweetalert2';

const ReviewsList = () => {
  const [searchTerm, setSearchTerm] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  
  // Applied filters state
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [appliedStartDate, setAppliedStartDate] = useState("");
  const [appliedEndDate, setAppliedEndDate] = useState("");
  
  const [reviews, setReviews] = useState([]);
  const [loading, setLoading] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showAddModal, setShowAddModal] = useState(false);
  const [editFormData, setEditFormData] = useState({
    review_name: "",
    review: "",
    profile_pic: null
  });
  const [addFormData, setAddFormData] = useState({
    review_name: "",
    review: "",
    profile_pic: null
  });
  const [editingReview, setEditingReview] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [uploadLoading, setUploadLoading] = useState(false);
  const router = useRouter();

  // Fetch reviews when page changes or applied filters change
  useEffect(() => {
    fetchReviews();
  }, [currentPage, appliedSearchTerm, appliedStartDate, appliedEndDate]);

  const fetchReviews = async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString()
      });
      
      if (appliedSearchTerm) {
        params.append('search', appliedSearchTerm);
      }
      
      if (appliedStartDate) {
        params.append('startDate', appliedStartDate);
      }
      
      if (appliedEndDate) {
        params.append('endDate', appliedEndDate);
      }

      const res = await fetch(`/api/internal/reviews?${params.toString()}`);
      if (!res.ok) throw new Error("Failed to fetch reviews");

      const data = await res.json();
      if (data.success) {
        setReviews(data.data || []);
        setTotalItems(data.meta?.totalItems || 0);
        setTotalPages(data.meta?.totalPages || 1);
      } else {
        setReviews([]);
        setTotalItems(0);
        setTotalPages(1);
      }
    } catch (err) {
      console.error("Fetch error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to load reviews',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
      setReviews([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id) => {
    try {
      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!',
        cancelButtonText: 'Cancel'
      });

      if (result.isConfirmed) {
        const res = await fetch(`/api/internal/reviews?id=${id}`, {
          method: "DELETE",
        });

        if (!res.ok) throw new Error("Failed to delete review");

        fetchReviews();
        
        Swal.fire({
          icon: 'success',
          title: 'Deleted!',
          text: 'Review has been deleted successfully.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
      }
    } catch (err) {
      console.error("Delete error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to delete review',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    }
  };

  const handleEdit = (review) => {
    setEditingReview(review);
    setEditFormData({
      review_name: review.review_name || "",
      review: review.review || "",
      profile_pic: null
    });
    setShowEditModal(true);
  };

  const handleFileChange = (e, isEdit = false) => {
    const file = e.target.files[0];
    if (file) {
      if (!file.type.startsWith('image/')) {
        Swal.fire({
          icon: 'error',
          title: 'Invalid File',
          text: 'Please select an image file',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        return;
      }
      
      if (file.size > 5 * 1024 * 1024) { // 5MB limit
        Swal.fire({
          icon: 'error',
          title: 'File Too Large',
          text: 'Please select an image smaller than 5MB',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        return;
      }

      if (isEdit) {
        setEditFormData(prev => ({ ...prev, profile_pic: file }));
      } else {
        setAddFormData(prev => ({ ...prev, profile_pic: file }));
      }
    }
  };

  const removeImage = (isEdit = false) => {
    if (isEdit) {
      setEditFormData(prev => ({ ...prev, profile_pic: null }));
    } else {
      setAddFormData(prev => ({ ...prev, profile_pic: null }));
    }
  };

  const handleSaveEdit = async () => {
    try {
      if (!editFormData.review_name || !editFormData.review) {
        Swal.fire({
          icon: 'warning',
          title: 'Validation Error!',
          text: 'Please fill in all required fields',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        return;
      }

      setUploadLoading(true);

      const formData = new FormData();
      formData.append('id', editingReview.id);
      formData.append('review_name', editFormData.review_name);
      formData.append('review', editFormData.review);
      
      if (editFormData.profile_pic) {
        formData.append('profile_pic', editFormData.profile_pic);
      } else if (!editingReview.profile_pic) {
        formData.append('removeImage', 'true');
      }

      const res = await fetch(`/api/internal/reviews`, {
        method: "PUT",
        body: formData,
      });

      if (!res.ok) throw new Error("Failed to update review");

      const result = await res.json();
      
      if (result.success) {
        fetchReviews();
        setShowEditModal(false);
        setEditingReview(null);
        setEditFormData({
          review_name: "",
          review: "",
          profile_pic: null
        });

        Swal.fire({
          icon: 'success',
          title: 'Updated!',
          text: 'Review has been updated successfully.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
      } else {
        throw new Error(result.message);
      }
    } catch (err) {
      console.error("Update error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: err.message || 'Failed to update review',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    } finally {
      setUploadLoading(false);
    }
  };

  const handleAdd = async () => {
    try {
      if (!addFormData.review_name || !addFormData.review) {
        Swal.fire({
          icon: 'warning',
          title: 'Validation Error!',
          text: 'Please fill in all required fields',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
        return;
      }

      setUploadLoading(true);

      const formData = new FormData();
      formData.append('review_name', addFormData.review_name);
      formData.append('review', addFormData.review);
      
      if (addFormData.profile_pic) {
        formData.append('profile_pic', addFormData.profile_pic);
      }

      const res = await fetch(`/api/internal/reviews`, {
        method: "POST",
        body: formData,
      });

      if (!res.ok) throw new Error("Failed to add review");

      const result = await res.json();
      
      if (result.success) {
        fetchReviews();
        setShowAddModal(false);
        setAddFormData({
          review_name: "",
          review: "",
          profile_pic: null
        });

        Swal.fire({
          icon: 'success',
          title: 'Added!',
          text: 'Review has been added successfully.',
          confirmButtonColor: '#0B6D76',
          confirmButtonText: 'OK'
        });
      } else {
        throw new Error(result.message);
      }
    } catch (err) {
      console.error("Add error:", err);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: err.message || 'Failed to add review',
        confirmButtonColor: '#0B6D76',
        confirmButtonText: 'OK'
      });
    } finally {
      setUploadLoading(false);
    }
  };

  const handleSearch = () => {
    setAppliedSearchTerm(searchTerm);
    setAppliedStartDate(startDate);
    setAppliedEndDate(endDate);
    setCurrentPage(1);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setStartDate("");
    setEndDate("");
    setAppliedSearchTerm("");
    setAppliedStartDate("");
    setAppliedEndDate("");
    setCurrentPage(1);
  };

  const hasActiveFilters = appliedSearchTerm || appliedStartDate || appliedEndDate;

  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + reviews.length;

  const getImagePreview = (file, currentImage) => {
    if (file) {
      return URL.createObjectURL(file);
    }
    return currentImage;
  };

  return (
    <div className="p-4 sm:p-6 bg-gradient-to-br from-blue-50 to-cyan-100 min-h-screen">
      {/* Header */}
      <div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
        <div className="text-center md:text-left">
          <h1 className="text-3xl font-bold text-gray-900">Reviews List</h1>
          <p className="text-gray-600 mt-2">Manage all customer reviews</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={`px-4 py-2 rounded-lg transition-colors flex items-center gap-2 ${
              isFilterOpen 
                ? 'bg-[#0B6D76] text-white' 
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            🔍 Filters
            {hasActiveFilters && (
              <span className="ml-1 px-2 py-1 bg-white text-[#0B6D76] text-xs rounded-full">
                {[appliedSearchTerm, appliedStartDate, appliedEndDate].filter(Boolean).length}
              </span>
            )}
          </button>
          <button
            onClick={() => setShowAddModal(true)}
            className="bg-blue-600 text-white px-6 py-3 rounded-xl hover:bg-blue-700 transition-colors flex items-center gap-2"
          >
            <Plus className="w-5 h-5" />
            Add Review
          </button>
        </div>
      </div>

      {/* Filter Section */}
      {isFilterOpen && (
        <div className="bg-white rounded-2xl shadow-xl p-6 mb-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Search Reviews</label>
              <input
                type="text"
                placeholder="Search by name or review..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && handleSearch()}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">Start Date</label>
              <input
                type="date"
                value={startDate}
                onChange={(e) => setStartDate(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">End Date</label>
              <input
                type="date"
                value={endDate}
                onChange={(e) => setEndDate(e.target.value)}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
              />
            </div>
          </div>
          
          <div className="flex justify-between items-center mt-4 pt-4 border-t border-gray-200">
            <div className="flex gap-2">
              <button
                onClick={handleSearch}
                className="px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#094F56] transition-colors flex items-center gap-2"
              >
                🔍 Search
              </button>
              {hasActiveFilters && (
                <button
                  onClick={clearFilters}
                  className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
                >
                  Clear Filters
                </button>
              )}
            </div>
            
            {/* Active Filters Display */}
            {hasActiveFilters && (
              <div className="text-sm text-gray-600">
                Active filters: 
                {appliedSearchTerm && <span className="ml-2 px-2 py-1 bg-blue-100 text-blue-800 rounded">Search: "{appliedSearchTerm}"</span>}
                {appliedStartDate && <span className="ml-2 px-2 py-1 bg-green-100 text-green-800 rounded">Start: {appliedStartDate}</span>}
                {appliedEndDate && <span className="ml-2 px-2 py-1 bg-purple-100 text-purple-800 rounded">End: {appliedEndDate}</span>}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Table */}
      <div className="bg-white rounded-2xl shadow-xl p-6">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[900px]">
            <thead className="sticky top-0 bg-gradient-to-r from-blue-50 to-cyan-50 z-10">
              <tr>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900 rounded-l-xl">ID</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Profile</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Reviewer Name</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Review</th>
                <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Created Date</th>
                <th className="py-3 px-4 text-center text-sm font-semibold text-gray-900 rounded-r-xl">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {loading ? (
                <tr>
                  <td colSpan="6" className="py-6 text-center text-gray-500">Loading...</td>
                </tr>
              ) : reviews.length === 0 ? (
                <tr>
                  <td colSpan="6" className="py-6 text-center text-gray-500">
                    {hasActiveFilters ? 'No reviews found matching your filters.' : 'No reviews available.'}
                  </td>
                </tr>
              ) : (
                reviews.map((review) => (
                  <tr key={review.id} className="hover:bg-gray-50 transition-colors">
                    <td className="py-3 px-4 font-medium text-gray-900">#{review.id}</td>
                    <td className="py-3 px-4">
                      {review.profile_pic ? (
                        <img 
                          src={review.profile_pic} 
                          alt={review.review_name}
                          className="w-10 h-10 rounded-full object-cover"
                        />
                      ) : (
                        <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                          <span className="text-gray-500 text-sm">No Image</span>
                        </div>
                      )}
                    </td>
                    <td className="py-3 px-4 font-medium text-gray-900">{review.review_name}</td>
                    <td className="py-3 px-4 text-gray-600 max-w-xs truncate">{review.review}</td>
                    <td className="py-3 px-4 text-gray-600">
                      {new Date(review.created_at).toLocaleDateString()}
                    </td>
                    <td className="py-3 px-4 text-center">
                      <div className="flex justify-center gap-2">
                        <button
                          onClick={() => handleEdit(review)}
                          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(review.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 && (
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={setCurrentPage}
            totalItems={totalItems}
            startIndex={startIndex}
            endIndex={endIndex}
          />
        )}
      </div>

      {/* Edit Modal */}
      {showEditModal && editingReview && (
        <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 max-h-[90vh] overflow-y-auto">
            <button
              onClick={() => setShowEditModal(false)}
              className="absolute top-4 right-4 text-gray-500 hover:text-gray-700"
            >
              <X className="w-5 h-5" />
            </button>
            
            <h2 className="text-lg font-semibold mb-4">Edit Review</h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Reviewer Name *</label>
                <input
                  type="text"
                  value={editFormData.review_name}
                  onChange={(e) => setEditFormData({...editFormData, review_name: e.target.value})}
                  className="w-full border px-3 py-2 rounded"
                  placeholder="Enter reviewer name"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1">Review *</label>
                <textarea
                  value={editFormData.review}
                  onChange={(e) => setEditFormData({...editFormData, review: e.target.value})}
                  className="w-full border px-3 py-2 rounded"
                  rows="4"
                  placeholder="Enter review text"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1">Profile Picture</label>
                
                {/* Current Image Preview */}
                {(editingReview.profile_pic || editFormData.profile_pic) && (
                  <div className="mb-3">
                    <p className="text-sm text-gray-600 mb-2">Preview:</p>
                    <div className="relative inline-block">
                      <img 
                        src={getImagePreview(editFormData.profile_pic, editingReview.profile_pic)} 
                        alt="Preview"
                        className="w-20 h-20 rounded-full object-cover"
                      />
                      <button
                        type="button"
                        onClick={() => removeImage(true)}
                        className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1"
                      >
                        <XCircle className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                )}
                
                {/* File Upload */}
                <div className="flex items-center gap-3">
                  <label className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg cursor-pointer hover:bg-blue-700">
                    <Upload className="w-4 h-4" />
                    Upload Image
                    <input
                      type="file"
                      accept="image/*"
                      onChange={(e) => handleFileChange(e, true)}
                      className="hidden"
                    />
                  </label>
                  <span className="text-sm text-gray-500">JPEG, PNG, WebP (Max 5MB)</span>
                </div>
              </div>
            </div>
            
            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => setShowEditModal(false)}
                className="px-4 py-2 border rounded hover:bg-gray-100"
                disabled={uploadLoading}
              >
                Cancel
              </button>
              <button
                onClick={handleSaveEdit}
                disabled={uploadLoading}
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2"
              >
                {uploadLoading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                    Saving...
                  </>
                ) : (
                  'Save Changes'
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Add Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-none 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 max-h-[90vh] overflow-y-auto">
            <button
              onClick={() => setShowAddModal(false)}
              className="absolute top-4 right-4 text-gray-500 hover:text-gray-700"
            >
              <X className="w-5 h-5" />
            </button>
            
            <h2 className="text-lg font-semibold mb-4">Add New Review</h2>
            
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1">Reviewer Name *</label>
                <input
                  type="text"
                  value={addFormData.review_name}
                  onChange={(e) => setAddFormData({...addFormData, review_name: e.target.value})}
                  className="w-full border px-3 py-2 rounded"
                  placeholder="Enter reviewer name"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1">Review *</label>
                <textarea
                  value={addFormData.review}
                  onChange={(e) => setAddFormData({...addFormData, review: e.target.value})}
                  className="w-full border px-3 py-2 rounded"
                  rows="4"
                  placeholder="Enter review text"
                />
              </div>
              
              <div>
                <label className="block text-sm font-medium mb-1">Profile Picture</label>
                
                {/* Image Preview */}
                {addFormData.profile_pic && (
                  <div className="mb-3">
                    <p className="text-sm text-gray-600 mb-2">Preview:</p>
                    <div className="relative inline-block">
                      <img 
                        src={URL.createObjectURL(addFormData.profile_pic)} 
                        alt="Preview"
                        className="w-20 h-20 rounded-full object-cover"
                      />
                      <button
                        type="button"
                        onClick={() => removeImage(false)}
                        className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1"
                      >
                        <XCircle className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                )}
                
                {/* File Upload */}
                <div className="flex items-center gap-3">
                  <label className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg cursor-pointer hover:bg-blue-700">
                    <Upload className="w-4 h-4" />
                    Upload Image
                    <input
                      type="file"
                      accept="image/*"
                      onChange={(e) => handleFileChange(e, false)}
                      className="hidden"
                    />
                  </label>
                  <span className="text-sm text-gray-500">JPEG, PNG, WebP (Max 5MB)</span>
                </div>
              </div>
            </div>
            
            <div className="flex justify-end gap-3 mt-6">
              <button
                onClick={() => setShowAddModal(false)}
                className="px-4 py-2 border rounded hover:bg-gray-100"
                disabled={uploadLoading}
              >
                Cancel
              </button>
              <button
                onClick={handleAdd}
                disabled={uploadLoading}
                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2"
              >
                {uploadLoading ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                    Adding...
                  </>
                ) : (
                  'Add Review'
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ReviewsList;