"use client";

import { useState, useEffect, useCallback } from "react";
import { Plus, Edit, Trash2, Eye, X, Upload, Star } from "lucide-react";
import Pagination from "../components/Pagination";
import Swal from 'sweetalert2';
import Layout from "../components/Layout";
import Image from "next/image";

const SuccessStories = () => {
  const [stories, setStories] = useState([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);

  // Modal states
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showPreviewModal, setShowPreviewModal] = useState(false);
  const [selectedStory, setSelectedStory] = useState(null);

  // Form states
  const [formData, setFormData] = useState({
    alt_text: "",
    story_date: "",
    is_featured: false,
    image: null
  });
  const [imagePreview, setImagePreview] = useState(null);
  const [uploading, setUploading] = useState(false);

  const fetchStories = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: itemsPerPage.toString(),
      });

      const response = await fetch(`/api/internal/success-stories?${params.toString()}`);
      
      if (!response.ok) {
        throw new Error('Failed to fetch success stories');
      }
      
      const data = await response.json();
      
      if (data.success) {
        setStories(data.stories || []);
        setTotalItems(data.meta?.totalItems || 0);
        setTotalPages(data.meta?.totalPages || 1);
      } else {
        setStories([]);
        setTotalItems(0);
        setTotalPages(1);
      }
    } catch (error) {
      console.error("Fetch error:", error);
      Swal.fire({
        icon: "error",
        title: "Error",
        text: "Failed to fetch success stories",
      });
      setStories([]);
      setTotalItems(0);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  }, [currentPage, itemsPerPage]);

  useEffect(() => {
    fetchStories();
  }, [fetchStories]);

  const handleImageUpload = async (file) => {
    if (!file) return null;

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

      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) => {
    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;
      }

      setFormData(prev => ({ ...prev, image: file }));
      
      // Create preview
      const reader = new FileReader();
      reader.onload = (e) => {
        setImagePreview(e.target.result);
      };
      reader.readAsDataURL(file);
    }
  };

  const resetForm = () => {
    setFormData({
      alt_text: "",
      story_date: "",
      is_featured: false,
      image: null
    });
    setImagePreview(null);
  };

  const openAddModal = () => {
    resetForm();
    setShowAddModal(true);
  };

  const openEditModal = (story) => {
    setSelectedStory(story);

    const formatDateForInput = (dateString) => {
        if (!dateString) return '';
        try {
        const date = new Date(dateString);
        return date.toISOString().split('T')[0]; // Convert to YYYY-MM-DD
        } catch (e) {
        return '';
        }
    };

    setFormData({
      alt_text: story.alt_text || "",
      story_date: formatDateForInput(story.story_date) || "",
      is_featured: story.is_featured || false,
      image: null
    });
    setImagePreview(story.image ? getImageUrl(story.image) : null);
    setShowEditModal(true);
  };

  const openPreviewModal = (story) => {
    setSelectedStory(story);
    setShowPreviewModal(true);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!formData.alt_text.trim() || !formData.story_date.trim()) {
      Swal.fire({
        icon: 'warning',
        title: 'Validation Error',
        text: 'Please fill in all required fields.',
      });
      return;
    }

    try {
      let imageKey = null;

      // Upload image if new one is selected
      if (formData.image) {
        imageKey = await handleImageUpload(formData.image);
        if (!imageKey) return; // Upload failed
      } else if (showEditModal && selectedStory.image) {
        // Keep existing image if no new image is selected in edit mode
        imageKey = selectedStory.image;
      }

      const storyData = {
        alt_text: formData.alt_text,
        story_date: formData.story_date,
        is_featured: formData.is_featured,
        ...(imageKey && { image: imageKey })
      };

      const url = showEditModal 
        ? `/api/internal/success-stories?id=${selectedStory.id}`
        : '/api/internal/success-stories';
      
      const method = showEditModal ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(storyData),
      });

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

      const result = await response.json();

      if (result.success) {
        Swal.fire({
          icon: 'success',
          title: 'Success!',
          text: showEditModal ? 'Story updated successfully!' : 'Story created successfully!',
          confirmButtonColor: '#0B6D76',
        });
        
        if (showEditModal) {
          setShowEditModal(false);
        } else {
          setShowAddModal(false);
        }
        
        resetForm();
        fetchStories();
      }
    } catch (error) {
      console.error('Save error:', error);
      Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: 'Failed to save story. Please try again.',
        confirmButtonColor: '#0B6D76',
      });
    }
  };

  const handleDelete = (story) => {
    Swal.fire({
      title: 'Are you sure?',
      text: `You are about to delete "${story.alt_text}". This action cannot be undone.`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'Cancel'
    }).then(async (result) => {
      if (result.isConfirmed) {
        try {
          const response = await fetch(`/api/internal/success-stories?id=${story.id}`, {
            method: 'DELETE',
          });

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

          const result = await response.json();

          if (result.success) {
            Swal.fire({
              icon: 'success',
              title: 'Deleted!',
              text: 'Story has been deleted successfully.',
              confirmButtonColor: '#0B6D76',
            });
            fetchStories();
          }
        } catch (error) {
          console.error('Delete error:', error);
          Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'Failed to delete story. Please try again.',
            confirmButtonColor: '#0B6D76',
          });
        }
      }
    });
  };

  const getImageUrl = (imagePath) => {
    if (!imagePath) return null;
    return `https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${imagePath}`;
  };

  const formatDate = (dateString) => {
    if (!dateString) return 'N/A';
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
      });
    } catch (e) {
      return 'N/A';
    }
  };

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

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-cyan-100 flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#0B6D76]"></div>
      </div>
    );
  }

  return (
    <Layout>
      <div className="space-y-6 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">Success Stories</h1>
            <p className="text-gray-600 mt-2">Manage inspiring success stories</p>
          </div>
          <button
            onClick={openAddModal}
            className="px-6 py-3 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors flex items-center gap-2 font-medium"
          >
            <Plus size={20} />
            Add New Story
          </button>
        </div>

        {/* Stories Table */}
        <div className="bg-white rounded-2xl shadow-xl p-6 overflow-x-auto">
          <table className="w-full min-w-[800px]">
            <thead className="sticky top-0 bg-gradient-to-r from-blue-50 to-cyan-50 z-10">
              <tr>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900 rounded-l-xl">#</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Image</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Alt Text</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Story Data</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Featured</th>
                <th className="px-6 py-4 text-left text-sm font-semibold text-gray-900">Created At</th>
                <th className="px-6 py-4 text-center text-sm font-semibold text-gray-900 rounded-r-xl">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {stories.map((story, index) => (
                <tr key={story.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4 text-gray-600">{startIndex + index + 1}</td>
                  <td className="px-6 py-4">
                    {story.image ? (
                      <div className="relative w-16 h-16 rounded-lg overflow-hidden border border-gray-200">
                        <Image
                          src={getImageUrl(story.image)}
                          alt={story.alt_text}
                          fill
                          className="object-cover"
                        />
                      </div>
                    ) : (
                      <div className="w-16 h-16 bg-gray-100 rounded-lg border border-gray-200 flex items-center justify-center">
                        <span className="text-gray-400 text-xs">No Image</span>
                      </div>
                    )}
                  </td>
                  <td className="px-6 py-4">
                    <div className="max-w-xs">
                      <p className="font-medium text-gray-900 truncate" title={story.alt_text}>
                        {story.alt_text}
                      </p>
                    </div>
                  </td>
                  <td className="px-6 py-4">
                    <div className="max-w-xs">
                        <p className="text-gray-700 truncate" title={new Date(story.story_date).toLocaleDateString('en-US', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric'
                        })}>
                        {formatDate(story.story_date)}
                        </p>
                    </div>
                    </td>
                  <td className="px-6 py-4">
                    {story.is_featured ? (
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                        <Star size={12} className="mr-1" />
                        Featured
                      </span>
                    ) : (
                      <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                        Regular
                      </span>
                    )}
                  </td>
                  <td className="px-6 py-4 text-sm text-gray-500">
                    {formatDate(story.created_at)}
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex justify-center gap-2">
                      <button
                        onClick={() => openPreviewModal(story)}
                        className="p-2 text-blue-600 hover:bg-blue-100 rounded-lg transition-colors"
                        title="Preview Story"
                      >
                        <Eye size={16} />
                      </button>
                      <button
                        onClick={() => openEditModal(story)}
                        className="p-2 text-green-600 hover:bg-green-100 rounded-lg transition-colors"
                        title="Edit Story"
                      >
                        <Edit size={16} />
                      </button>
                      <button
                        onClick={() => handleDelete(story)}
                        className="p-2 text-red-600 hover:bg-red-100 rounded-lg transition-colors"
                        title="Delete Story"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {stories.length === 0 && (
            <div className="text-center py-12">
              <div className="text-gray-500 text-lg">
                No success stories available.
              </div>
              <p className="text-gray-400 mt-2">
                Get started by creating your first success story
              </p>
              <button
                onClick={openAddModal}
                className="mt-4 px-6 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors"
              >
                Create First Story
              </button>
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <Pagination
              currentPage={currentPage}
              totalPages={totalPages}
              onPageChange={setCurrentPage}
              totalItems={totalItems}
              startIndex={startIndex + 1}
              endIndex={endIndex}
            />
          )}
        </div>

        {/* Add/Edit Story Modal */}
        {(showAddModal || showEditModal) && (
          <StoryModal
            isOpen={showAddModal || showEditModal}
            isEdit={showEditModal}
            formData={formData}
            imagePreview={imagePreview}
            uploading={uploading}
            onClose={() => {
              if (showEditModal) {
                setShowEditModal(false);
              } else {
                setShowAddModal(false);
              }
              resetForm();
            }}
            onSubmit={handleSubmit}
            onImageChange={handleImageChange}
            onFormChange={(field, value) => setFormData(prev => ({ ...prev, [field]: value }))}
          />
        )}

        {/* Preview Modal */}
        {showPreviewModal && selectedStory && (
          <PreviewModal
            story={selectedStory}
            onClose={() => setShowPreviewModal(false)}
            getImageUrl={getImageUrl}
          />
        )}
      </div>
    </Layout>
  );
};

// Story Modal Component
const StoryModal = ({ 
  isOpen, 
  isEdit, 
  formData, 
  imagePreview, 
  uploading, 
  onClose, 
  onSubmit, 
  onImageChange, 
  onFormChange 
}) => {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          {/* Header */}
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-bold text-gray-900">
              {isEdit ? 'Edit Success Story' : 'Add New Success Story'}
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          <form onSubmit={onSubmit} className="space-y-6">
            {/* Image Upload */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                Story Image
              </label>
              <div className="flex flex-col sm:flex-row gap-6">
                {/* Image Preview */}
                <div className="flex-shrink-0">
                  <div className="w-48 h-48 border-2 border-dashed border-gray-300 rounded-lg flex items-center justify-center overflow-hidden">
                    {imagePreview ? (
                      <div className="relative w-full h-full">
                        <Image
                          src={imagePreview}
                          alt="Preview"
                          fill
                          className="object-cover"
                        />
                      </div>
                    ) : (
                      <div className="text-center p-4">
                        <Upload className="mx-auto h-12 w-12 text-gray-400" />
                        <span className="mt-2 block text-sm font-medium text-gray-900">
                          Upload image
                        </span>
                        <span className="mt-1 block text-xs text-gray-500">
                          PNG, JPG, GIF up to 5MB
                        </span>
                      </div>
                    )}
                  </div>
                </div>

                {/* Upload Controls */}
                <div className="flex-1 space-y-4">
                  <div>
                    <input
                      type="file"
                      id="image-upload"
                      accept="image/*"
                      onChange={onImageChange}
                      className="hidden"
                    />
                    <label
                      htmlFor="image-upload"
                      className="cursor-pointer inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#0B6D76]"
                    >
                      <Upload size={16} className="mr-2" />
                      Choose Image
                    </label>
                  </div>

                  {uploading && (
                    <div className="flex items-center text-sm text-gray-600">
                      <div className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-[#0B6D76] mr-2"></div>
                      Uploading image...
                    </div>
                  )}

                  <div className="text-sm text-gray-500">
                    <p>• Recommended size: 800x600px</p>
                    <p>• Supported formats: JPG, PNG, GIF, WebP</p>
                    <p>• Maximum file size: 5MB</p>
                  </div>
                </div>
              </div>
            </div>

            {/* Alt Text */}
            <div>
              <label htmlFor="alt_text" className="block text-sm font-medium text-gray-700 mb-2">
                Alt Text *
              </label>
              <input
                type="text"
                id="alt_text"
                value={formData.alt_text}
                onChange={(e) => onFormChange('alt_text', 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"
                placeholder="Enter descriptive alt text for the image"
                required
              />
            </div>

            {/* Story Date */}
            <div>
                <label htmlFor="story_date" className="block text-sm font-medium text-gray-700 mb-2">
                    Story Date *
                </label>
                <input
                    type="date"
                    id="story_date"
                    value={formData.story_date}
                    onChange={(e) => onFormChange('story_date', 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"
                    required
                />
            </div>

            {/* Featured Toggle */}
            <div className="flex items-center">
              <input
                type="checkbox"
                id="is_featured"
                checked={formData.is_featured}
                onChange={(e) => onFormChange('is_featured', e.target.checked)}
                className="h-4 w-4 text-[#0B6D76] focus:ring-[#0B6D76] border-gray-300 rounded"
              />
              <label htmlFor="is_featured" className="ml-2 block text-sm text-gray-700 flex items-center">
                <Star size={16} className="mr-1 text-yellow-500" />
                Mark as featured story
              </label>
            </div>

            {/* Action Buttons */}
            <div className="flex justify-end space-x-3 pt-6 border-t">
              <button
                type="button"
                onClick={onClose}
                className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium"
              >
                Cancel
              </button>
              <button
                type="submit"
                disabled={uploading}
                className="px-6 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#085a61] transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {uploading ? 'Uploading...' : (isEdit ? 'Update Story' : 'Create Story')}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

// Preview Modal Component
const PreviewModal = ({ story, onClose, getImageUrl }) => {
  return (
    <div className="fixed inset-0 bg-black/70 bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div className="bg-white rounded-xl max-w-4xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6">
          {/* Header */}
          <div className="flex justify-between items-center mb-6">
            <h2 className="text-2xl font-bold text-gray-900">
              Story Preview - {story.alt_text}
            </h2>
            <button
              onClick={onClose}
              className="text-gray-400 hover:text-gray-600 text-2xl p-2 hover:bg-gray-100 rounded-full transition-colors"
            >
              <X size={24} />
            </button>
          </div>

          <div className="space-y-6">
            {/* Image */}
            {story.image && (
              <div className="relative w-full h-80 rounded-lg overflow-hidden">
                <Image
                  src={getImageUrl(story.image)}
                  alt={story.alt_text}
                  fill
                  className="object-cover"
                />
              </div>
            )}

            {/* Story Details */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="md:col-span-2 space-y-4">
                <div>
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">Alt Text</h3>
                  <p className="text-gray-700">{story.alt_text}</p>
                </div>
                
                <div>
                    <h3 className="text-lg font-semibold text-gray-900 mb-2">Story Date</h3>
                    <p className="text-gray-700 whitespace-pre-wrap">
                        {new Date(story.story_date).toLocaleDateString('en-US', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric'
                        })}
                    </p>
                </div>
              </div>

              <div className="space-y-4">
                <div className="bg-gray-50 rounded-lg p-4">
                  <h3 className="text-lg font-semibold text-gray-900 mb-3">Story Info</h3>
                  
                  <div className="space-y-3">
                    <div>
                      <span className="text-sm font-medium text-gray-500">Status:</span>
                      <div className="mt-1">
                        {story.is_featured ? (
                          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                            <Star size={12} className="mr-1" />
                            Featured
                          </span>
                        ) : (
                          <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                            Regular
                          </span>
                        )}
                      </div>
                    </div>
                    
                    <div>
                      <span className="text-sm font-medium text-gray-500">Created:</span>
                      <p className="text-sm text-gray-900 mt-1">
                        {new Date(story.created_at).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric'
                        })}
                      </p>
                    </div>
                    
                    <div>
                      <span className="text-sm font-medium text-gray-500">Last Updated:</span>
                      <p className="text-sm text-gray-900 mt-1">
                        {new Date(story.updated_at).toLocaleDateString('en-US', {
                          year: 'numeric',
                          month: 'long',
                          day: 'numeric',
                          hour: '2-digit',
                          minute: '2-digit'
                        })}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Close Button */}
          <div className="mt-6 flex justify-end">
            <button
              onClick={onClose}
              className="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors font-medium"
            >
              Close Preview
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SuccessStories;