"use client";

import { useState, useEffect } from "react";
import { Plus, Edit, Trash2, Filter, X, Search, RefreshCw } from "lucide-react";
import { useRouter } from "next/navigation";
import Pagination from "../../admin/components/Pagination";
import Swal from 'sweetalert2';

const SiloRoutesList = () => {
  const [routes, setRoutes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [appliedSearchTerm, setAppliedSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(15);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [isFilterOpen, setIsFilterOpen] = useState(false);
  const router = useRouter();

  useEffect(() => {
    fetchRoutes();
  }, [currentPage, appliedSearchTerm]);

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

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

  const handleDelete = async (id) => {
    const result = await Swal.fire({
      title: 'Are you sure?',
      text: "This will permanently delete this silo route!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#d33',
      cancelButtonColor: '#3085d6',
      confirmButtonText: 'Yes, delete it!'
    });

    if (!result.isConfirmed) return;

    try {
      const res = await fetch(`/api/internal/silo-routes?id=${id}`, {
        method: "DELETE",
      });
      
      if (!res.ok) throw new Error("Failed to delete silo route");

      fetchRoutes();
      
      Swal.fire({
        icon: 'success',
        title: 'Deleted!',
        text: 'Silo route has been deleted.',
      });
    } catch (error) {
      console.error(error);
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: "Error deleting silo route",
      });
    }
  };

  const applyFilters = () => {
    setAppliedSearchTerm(searchTerm);
    setCurrentPage(1);
    setIsFilterOpen(false);
  };

  const clearFilters = () => {
    setSearchTerm("");
    setAppliedSearchTerm("");
    setCurrentPage(1);
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const truncateText = (text, length = 60) => {
    if (!text) return '';
    if (text.length <= length) return text;
    return text.substring(0, length) + '...';
  };

  const hasActiveFilters = appliedSearchTerm;

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

  return (
    <div className="p-6 bg-gradient-to-br from-blue-50 to-cyan-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">Silo Routes</h1>
            <p className="text-gray-600 text-sm sm:text-base">Manage silo routes and their content</p>
          </div>
          <div className="flex gap-3">
            <button
              onClick={fetchRoutes}
              className="bg-gray-600 text-white px-4 py-3 rounded-xl hover:bg-gray-700 transition-colors flex items-center gap-2"
            >
              <RefreshCw className="w-5 h-5" />
              Refresh
            </button>
            <button
              onClick={() => router.push("/admin/silo-routes/add")}
              className="bg-[#0B6D76] text-white px-6 py-3 rounded-xl hover:bg-[#09545c] transition-colors flex items-center gap-2"
            >
              <Plus className="w-5 h-5" />
              Add Silo Route
            </button>
          </div>
        </div>

        {/* Filter Toggle Button */}
        <div className="mb-6">
          <button
            onClick={() => setIsFilterOpen(!isFilterOpen)}
            className={`px-6 py-3 rounded-xl transition-colors flex items-center gap-2 ${
              isFilterOpen || hasActiveFilters
                ? 'bg-[#0B6D76] text-white' 
                : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
            }`}
          >
            <Filter className="w-4 h-4" />
            {isFilterOpen ? 'Hide Filters' : 'Show Filters'}
            {hasActiveFilters && (
              <span className="ml-1 px-2 py-1 bg-white text-[#0B6D76] text-xs rounded-full">
                1
              </span>
            )}
          </button>
        </div>

        {/* Filter Panel */}
        {isFilterOpen && (
          <div className="bg-gray-50 rounded-xl p-6 border border-gray-200 mb-6">
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
              {/* Search Input */}
              <div className="lg:col-span-8">
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  Search Silo Routes
                </label>
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <input
                    type="text"
                    placeholder="Search by title, name, or description..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent"
                  />
                </div>
              </div>

              {/* Filter Actions */}
              <div className="lg:col-span-4 flex items-end gap-2">
                <button
                  onClick={applyFilters}
                  className="flex-1 px-4 py-2 bg-[#0B6D76] text-white rounded-lg hover:bg-[#09545c] transition-colors flex items-center justify-center gap-2"
                >
                  <Search className="w-4 h-4" />
                  Apply
                </button>
                <button
                  onClick={clearFilters}
                  className="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition-colors"
                >
                  Clear
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Active Filters Display */}
        {hasActiveFilters && (
          <div className="flex flex-wrap gap-2 mb-6">
            {appliedSearchTerm && (
              <span className="inline-flex items-center gap-1 px-3 py-1 bg-blue-100 text-blue-800 text-sm rounded-full">
                Search: {appliedSearchTerm}
                <button onClick={() => setAppliedSearchTerm("")} className="hover:text-blue-900">
                  <X className="w-3 h-3" />
                </button>
              </span>
            )}
          </div>
        )}

        {/* Table */}
        {loading ? (
          <div className="flex justify-center items-center py-12">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#0B6D76]"></div>
          </div>
        ) : routes.length === 0 ? (
          <div className="text-center py-12">
            <div className="text-gray-400 text-6xl mb-4">📍</div>
            <h3 className="text-lg font-semibold text-gray-600 mb-2">
              {hasActiveFilters ? 'No silo routes found' : 'No silo routes yet'}
            </h3>
            <p className="text-gray-500 mb-6">
              {hasActiveFilters 
                ? 'No silo routes matching your filters were found.'
                : 'Get started by adding your first silo route.'
              }
            </p>
            {!hasActiveFilters && (
              <button
                onClick={() => router.push("/admin/silo-routes/add")}
                className="bg-[#0B6D76] text-white px-6 py-3 rounded-xl hover:bg-[#09545c] transition-colors"
              >
                Add First Silo Route
              </button>
            )}
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full min-w-[1100px]">
                <thead className="bg-gray-50">
                  <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">Title</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Name</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Slug</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Short Description</th>
                    <th className="py-3 px-4 text-left text-sm font-semibold text-gray-900">Created</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">
                  {routes.map((route) => (
                    <tr key={route.id} className="hover:bg-gray-50 transition-colors">
                      <td className="py-3 px-4">
                        <span className="text-sm font-mono text-gray-600">#{route.id}</span>
                      </td>
                      <a href={`/${route.slug}`} target="_blank"><td className="py-3 px-4">
                        <div className="font-medium text-gray-900">
                          {route.simple_title}
                          {route.color_title && (
                            <span className="ml-2 text-blue-600">({route.color_title})</span>
                          )}
                        </div>
                      </td></a>
                      <td className="py-3 px-4">
                        <div className="text-gray-700">{route.name}</div>
                      </td>
                      <td className="py-3 px-4">
                        <code className="text-sm bg-gray-100 px-2 py-1 rounded text-gray-700">
                          {route.slug}
                        </code>
                      </td>
                      <td className="py-3 px-4">
                        <div className="text-sm text-gray-600" title={route.short_description}>
                          {truncateText(route.short_description, 50)}
                        </div>
                      </td>
                      <td className="py-3 px-4">
                        <div className="text-sm text-gray-600">
                          {formatDate(route.created_at)}
                        </div>
                      </td>
                      <td className="py-3 px-4 text-center">
                        <div className="flex justify-center gap-2">
                          <button
                            onClick={() => router.push(`/admin/silo-routes/edit/${route.id}`)}
                            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(route.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-8">
                <Pagination
                  currentPage={currentPage}
                  totalPages={totalPages}
                  onPageChange={setCurrentPage}
                  totalItems={totalItems}
                  startIndex={startIndex}
                  endIndex={endIndex}
                />
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
};

export default SiloRoutesList;