"use client";

/**
 * Blog Management Client Component
 * Main interface for managing blog posts in staff dashboard
 */

import { useState, useEffect } from "react";
import {
  Plus,
  Search,
  Filter,
  Trash2,
  Eye,
  EyeOff,
  Edit,
  Star,
  Archive,
} from "lucide-react";
import BlogPostModal from "./BlogPostModal";
import type {
  BlogPostListItem,
  BlogStats,
  BlogPostFilters,
} from "@/lib/types/blog-management.types";

export default function BlogManagementClient() {
  const [posts, setPosts] = useState<BlogPostListItem[]>([]);
  const [stats, setStats] = useState<BlogStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedPosts, setSelectedPosts] = useState<Set<string>>(new Set());
  const [showModal, setShowModal] = useState(false);
  const [editingPost, setEditingPost] = useState<BlogPostListItem | null>(null);
  const [filters, setFilters] = useState<BlogPostFilters>({});
  const [searchTerm, setSearchTerm] = useState("");
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  // Load posts and stats
  useEffect(() => {
    loadPosts();
    loadStats();
  }, [filters, page]);

  async function loadPosts() {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: "20",
      });

      if (filters.status) queryParams.append("status", filters.status);
      if (filters.lang) queryParams.append("lang", filters.lang);
      if (filters.featured !== undefined)
        queryParams.append("featured", filters.featured.toString());
      if (filters.search) queryParams.append("search", filters.search);

      const res = await fetch(`/api/staff/dashboard/blog?${queryParams}`, {
        cache: "no-store",
      });
      const data = await res.json();

      if (res.ok) {
        setPosts(data.posts || []);
        setTotalPages(data.totalPages || 1);
      }
    } catch (error) {
      console.error("Failed to load posts:", error);
    } finally {
      setLoading(false);
    }
  }

  async function loadStats() {
    try {
      const res = await fetch("/api/staff/dashboard/blog/stats", {
        cache: "no-store",
      });
      const data = await res.json();
      if (res.ok) {
        setStats(data.stats);
      }
    } catch (error) {
      console.error("Failed to load stats:", error);
    }
  }

  function handleSearch() {
    setFilters({ ...filters, search: searchTerm });
    setPage(1);
  }

  function handleFilterChange(key: keyof BlogPostFilters, value: any) {
    setFilters({ ...filters, [key]: value });
    setPage(1);
  }

  function handleEdit(post: BlogPostListItem) {
    setEditingPost(post);
    setShowModal(true);
  }

  function handleCreate() {
    setEditingPost(null);
    setShowModal(true);
  }

  async function handleDelete(id: string) {
    if (
      !confirm(
        "Are you sure you want to delete this blog post? This action cannot be undone.",
      )
    ) {
      return;
    }

    try {
      const res = await fetch(`/api/staff/dashboard/blog/${id}`, {
        method: "DELETE",
      });

      if (res.ok) {
        loadPosts();
        loadStats();
      } else {
        alert("Failed to delete blog post");
      }
    } catch (error) {
      console.error("Delete error:", error);
      alert("Failed to delete blog post");
    }
  }

  async function handleBulkStatusUpdate(
    status: "DRAFT" | "PUBLISHED" | "ARCHIVED",
  ) {
    if (selectedPosts.size === 0) return;

    try {
      const res = await fetch("/api/staff/dashboard/blog/bulk-update", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ids: Array.from(selectedPosts),
          status,
        }),
      });

      if (res.ok) {
        setSelectedPosts(new Set());
        loadPosts();
        loadStats();
      }
    } catch (error) {
      console.error("Bulk update error:", error);
    }
  }

  function toggleSelectPost(id: string) {
    const newSelected = new Set(selectedPosts);
    if (newSelected.has(id)) {
      newSelected.delete(id);
    } else {
      newSelected.add(id);
    }
    setSelectedPosts(newSelected);
  }

  function toggleSelectAll() {
    if (selectedPosts.size === posts.length) {
      setSelectedPosts(new Set());
    } else {
      setSelectedPosts(new Set(posts.map((p) => p.id)));
    }
  }

  const getStatusBadge = (status: string) => {
    const styles = {
      DRAFT: "bg-gray-100 text-gray-700",
      PUBLISHED: "bg-green-100 text-green-700",
      ARCHIVED: "bg-orange-100 text-orange-700",
    };
    return styles[status as keyof typeof styles] || styles.DRAFT;
  };

  return (
    <div className="space-y-6">
      {/* Stats Overview */}
      {stats && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <StatCard title="Total Posts" value={stats.total} icon="📝" />
          <StatCard
            title="Published"
            value={stats.byStatus.published}
            icon="✅"
            color="green"
          />
          <StatCard
            title="Drafts"
            value={stats.byStatus.draft}
            icon="📋"
            color="gray"
          />
          <StatCard
            title="Recently Published"
            value={stats.recentlyPublished}
            icon="🆕"
            color="blue"
          />
        </div>
      )}

      {/* Actions Bar */}
      <div className="flex flex-col lg:flex-row gap-4 items-start lg:items-center justify-between bg-white p-4 rounded-lg border">
        {/* Search */}
        <div className="flex gap-2 w-full lg:w-auto">
          <input
            type="text"
            placeholder="Search blog posts..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSearch()}
            className="flex-1 lg:w-64 px-4 py-2 border rounded-lg focus:ring-2 focus:ring-brand-green"
          />
          <button
            onClick={handleSearch}
            className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg transition"
          >
            <Search className="w-5 h-5" />
          </button>
        </div>

        {/* Filters & Actions */}
        <div className="flex gap-2 flex-wrap">
          {/* Status Filter */}
          <select
            value={filters.status || ""}
            onChange={(e) =>
              handleFilterChange("status", e.target.value || undefined)
            }
            className="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-brand-green"
          >
            <option value="">All Status</option>
            <option value="DRAFT">Draft</option>
            <option value="PUBLISHED">Published</option>
            <option value="ARCHIVED">Archived</option>
          </select>

          {/* Language Filter */}
          <select
            value={filters.lang || ""}
            onChange={(e) =>
              handleFilterChange("lang", e.target.value || undefined)
            }
            className="px-4 py-2 border rounded-lg focus:ring-2 focus:ring-brand-green"
          >
            <option value="">Both Languages</option>
            <option value="ar">Arabic</option>
            <option value="en">English</option>
          </select>

          {/* Create New Button */}
          <button
            onClick={handleCreate}
            className="px-6 py-2 bg-brand-green text-white rounded-lg hover:bg-emerald-600 transition flex items-center gap-2 font-semibold"
          >
            <Plus className="w-5 h-5" />
            Create Post
          </button>
        </div>
      </div>

      {/* Bulk Actions */}
      {selectedPosts.size > 0 && (
        <div className="flex items-center gap-3 p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <span className="font-semibold text-blue-900">
            {selectedPosts.size} selected
          </span>
          <button
            onClick={() => handleBulkStatusUpdate("PUBLISHED")}
            className="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition flex items-center gap-2"
          >
            <Eye className="w-4 h-4" />
            Publish
          </button>
          <button
            onClick={() => handleBulkStatusUpdate("DRAFT")}
            className="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600 transition flex items-center gap-2"
          >
            <EyeOff className="w-4 h-4" />
            Unpublish
          </button>
          <button
            onClick={() => handleBulkStatusUpdate("ARCHIVED")}
            className="px-4 py-2 bg-orange-500 text-white rounded-lg hover:bg-orange-600 transition flex items-center gap-2"
          >
            <Archive className="w-4 h-4" />
            Archive
          </button>
        </div>
      )}

      {/* Posts Table */}
      <div className="bg-white rounded-lg border overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50 border-b">
            <tr>
              <th className="p-4 text-left">
                <input
                  type="checkbox"
                  checked={
                    selectedPosts.size === posts.length && posts.length > 0
                  }
                  onChange={toggleSelectAll}
                  className="w-4 h-4 text-brand-green rounded"
                />
              </th>
              <th className="p-4 text-left font-semibold text-gray-700">
                Title
              </th>
              <th className="p-4 text-left font-semibold text-gray-700">
                Lang
              </th>
              <th className="p-4 text-left font-semibold text-gray-700">
                Status
              </th>
              <th className="p-4 text-left font-semibold text-gray-700">
                Author
              </th>
              <th className="p-4 text-left font-semibold text-gray-700">
                Date
              </th>
              <th className="p-4 text-left font-semibold text-gray-700">
                Actions
              </th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={7} className="p-8 text-center text-gray-500">
                  Loading...
                </td>
              </tr>
            ) : posts.length === 0 ? (
              <tr>
                <td colSpan={7} className="p-8 text-center text-gray-500">
                  No blog posts found
                </td>
              </tr>
            ) : (
              posts.map((post) => (
                <tr
                  key={post.id}
                  className="border-b hover:bg-gray-50 transition"
                >
                  <td className="p-4">
                    <input
                      type="checkbox"
                      checked={selectedPosts.has(post.id)}
                      onChange={() => toggleSelectPost(post.id)}
                      className="w-4 h-4 text-brand-green rounded"
                    />
                  </td>
                  <td className="p-4">
                    <div className="flex items-center gap-3">
                      {post.cover_image && (
                        <img
                          src={post.cover_image}
                          alt=""
                          className="w-12 h-12 rounded object-cover"
                        />
                      )}
                      <div>
                        <div className="font-medium text-gray-900 flex items-center gap-2">
                          {post.title}
                          {post.featured && (
                            <Star className="w-4 h-4 text-yellow-500 fill-yellow-500" />
                          )}
                        </div>
                        <div className="text-sm text-gray-500 truncate max-w-md">
                          {post.excerpt}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td className="p-4">
                    <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs font-medium uppercase">
                      {post.lang}
                    </span>
                  </td>
                  <td className="p-4">
                    <span
                      className={`px-3 py-1 rounded-full text-xs font-semibold ${getStatusBadge(post.status)}`}
                    >
                      {post.status}
                    </span>
                  </td>
                  <td className="p-4 text-sm text-gray-600">{post.author}</td>
                  <td className="p-4 text-sm text-gray-600">
                    {new Date(post.date).toLocaleDateString()}
                  </td>
                  <td className="p-4">
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => handleEdit(post)}
                        className="p-2 text-blue-600 hover:bg-blue-50 rounded transition"
                        title="Edit"
                      >
                        <Edit className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => handleDelete(post.id)}
                        className="p-2 text-red-600 hover:bg-red-50 rounded transition"
                        title="Delete"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="p-4 flex items-center justify-between border-t bg-gray-50">
            <button
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page === 1}
              className="px-4 py-2 border rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-white transition"
            >
              Previous
            </button>
            <span className="text-sm text-gray-600">
              Page {page} of {totalPages}
            </span>
            <button
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
              className="px-4 py-2 border rounded-lg disabled:opacity-50 disabled:cursor-not-allowed hover:bg-white transition"
            >
              Next
            </button>
          </div>
        )}
      </div>

      {/* Create/Edit Modal */}
      {showModal && (
        <BlogPostModal
          post={editingPost}
          onClose={() => {
            setShowModal(false);
            setEditingPost(null);
          }}
          onSuccess={() => {
            setShowModal(false);
            setEditingPost(null);
            loadPosts();
            loadStats();
          }}
        />
      )}
    </div>
  );
}

function StatCard({
  title,
  value,
  icon,
  color = "green",
}: {
  title: string;
  value: number;
  icon: string;
  color?: "green" | "gray" | "blue" | "orange";
}) {
  const colorClasses = {
    green: "bg-green-50 border-green-200",
    gray: "bg-gray-50 border-gray-200",
    blue: "bg-blue-50 border-blue-200",
    orange: "bg-orange-50 border-orange-200",
  };

  return (
    <div className={`p-6 rounded-lg border ${colorClasses[color]}`}>
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm text-gray-600 font-medium">{title}</p>
          <p className="text-3xl font-bold text-gray-900 mt-1">{value}</p>
        </div>
        <span className="text-4xl">{icon}</span>
      </div>
    </div>
  );
}
