/**
 * Category Issues Panel Component
 *
 * Slide-over panel showing issues for a specific category
 */

import React, { useState, useEffect } from "react";
import { __, sprintf } from "@wordpress/i18n";
import { Button, Select } from "../../../components/ui";
import {
  XMarkIcon,
  Cog6ToothIcon,
  DocumentTextIcon,
  BoltIcon,
  ShieldCheckIcon,
  DocumentDuplicateIcon,
  FunnelIcon,
  ChevronLeftIcon,
  ChevronRightIcon,
} from "@heroicons/react/24/outline";
import IssueDetailRow from "./IssueDetailRow";

const CategoryIssuesPanel = ({
  isOpen,
  onClose,
  category,
  issues = [],
  isLoading,
  pagination = { page: 1, total: 0, pages: 1 },
  onPageChange,
  onSeverityFilter,
  selectedSeverity = "all",
  onApplyFix,
  onIgnore,
  categoryScore = 0,
}) => {
  const [applyingFixId, setApplyingFixId] = useState(null);

  const getCategoryIcon = (categoryId) => {
    const icons = {
      "technical-seo": Cog6ToothIcon,
      technical_seo: Cog6ToothIcon,
      "on-page-seo": DocumentTextIcon,
      on_page_seo: DocumentTextIcon,
      performance: BoltIcon,
      security: ShieldCheckIcon,
      content: DocumentDuplicateIcon,
    };
    return icons[categoryId] || DocumentTextIcon;
  };

  const getCategoryColor = (categoryId) => {
    const colors = {
      "technical-seo": "#3b82f6",
      technical_seo: "#3b82f6",
      "on-page-seo": "#3b82f6",
      on_page_seo: "#3b82f6",
      performance: "#10b981",
      security: "#ef4444",
      content: "#f59e0b",
    };
    return colors[categoryId] || "#3b82f6";
  };

  const getScoreColor = (score) => {
    if (score >= 80) return "#10b981";
    if (score >= 60) return "#f59e0b";
    return "#ef4444";
  };

  const CategoryIcon = getCategoryIcon(category?.id);
  const categoryColor = getCategoryColor(category?.id);

  const handleApplyFix = async (issue) => {
    if (!onApplyFix) return;
    setApplyingFixId(issue.id);
    try {
      await onApplyFix(issue);
    } finally {
      setApplyingFixId(null);
    }
  };

  const severityOptions = [
    { value: "all", label: __("All Severities", "prorank-seo") },
    { value: "critical", label: __("Critical", "prorank-seo") },
    { value: "high", label: __("High", "prorank-seo") },
    { value: "medium", label: __("Medium", "prorank-seo") },
    { value: "low", label: __("Low", "prorank-seo") },
  ];

  if (!isOpen) return null;

  return (
    <>
      {/* Backdrop */}
      <div
        className="pr:fixed pr:inset-0 pr:top-[32px] pr:bg-black/30 pr:z-40 pr:transition-opacity pr:duration-300"
        onClick={onClose}
      />

      {/* Panel */}
      <div
        className={`pr:fixed pr:right-0 pr:top-[32px] pr:h-[calc(100%-32px)] pr:w-full pr:max-w-lg pr:bg-white pr:shadow-2xl pr:z-50 pr:flex pr:flex-col pr:transform pr:transition-transform pr:duration-300 ${
          isOpen ? "pr:translate-x-0" : "pr:translate-x-full"
        }`}
      >
        {/* Header */}
        <div
          className="pr:flex pr:items-center pr:justify-between pr:p-4 pr:border-b pr:border-gray-200"
          style={{ backgroundColor: categoryColor + "10" }}
        >
          <div className="pr:flex pr:items-center pr:gap-3">
            <div
              className="pr:p-2 pr:rounded-lg"
              style={{ backgroundColor: categoryColor + "20" }}
            >
              <CategoryIcon
                className="pr:w-6 pr:h-6"
                style={{ color: categoryColor }}
              />
            </div>
            <div>
              <h2 className="pr:text-lg pr:font-semibold pr:text-gray-900">
                {category?.name || category?.title || __("Category Issues", "prorank-seo")}
              </h2>
              <div className="pr:flex pr:items-center pr:gap-2">
                <span
                  className="pr:text-2xl pr:font-bold"
                  style={{ color: getScoreColor(categoryScore) }}
                >
                  {categoryScore}%
                </span>
                <span className="pr:text-sm pr:text-gray-500">
                  {sprintf(
                    __("%d issues found", "prorank-seo"),
                    pagination.total
                  )}
                </span>
              </div>
            </div>
          </div>
          <button
            onClick={onClose}
            className="pr:p-2 pr:rounded-lg pr:text-gray-400 pr:hover:text-gray-600 pr:hover:bg-gray-100 pr:transition-colors"
          >
            <XMarkIcon className="pr:w-6 pr:h-6" />
          </button>
        </div>

        {/* Filters */}
        <div className="pr:flex pr:items-center pr:gap-3 pr:p-4 pr:border-b pr:border-gray-200 pr:bg-gray-50">
          <FunnelIcon className="pr:w-5 pr:h-5 pr:text-gray-400" />
          <select
            value={selectedSeverity}
            onChange={(e) => onSeverityFilter && onSeverityFilter(e.target.value)}
            className="pr:flex-1 pr:px-3 pr:py-2 pr:border pr:border-gray-300 pr:rounded-lg pr:text-sm pr:bg-white pr:focus:ring-2 pr:focus:ring-blue-500 pr:focus:border-blue-500"
          >
            {severityOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </div>

        {/* Issue Count */}
        <div className="pr:px-4 pr:py-2 pr:bg-gray-50 pr:border-b pr:border-gray-200">
          <p className="pr:text-sm pr:text-gray-600">
            {sprintf(
              __("Showing %d of %d issues", "prorank-seo"),
              issues.length,
              pagination.total
            )}
          </p>
        </div>

        {/* Issues List */}
        <div className="pr:flex-1 pr:overflow-y-auto">
          {isLoading ? (
            <div className="pr:flex pr:items-center pr:justify-center pr:h-48">
              <div className="pr:flex pr:flex-col pr:items-center pr:gap-3">
                <div className="pr:w-8 pr:h-8 pr:border-2 pr:border-blue-500 pr:border-t-transparent pr:rounded-full pr:animate-spin" />
                <p className="pr:text-sm pr:text-gray-500">
                  {__("Loading issues...", "prorank-seo")}
                </p>
              </div>
            </div>
          ) : issues.length === 0 ? (
            <div className="pr:flex pr:items-center pr:justify-center pr:h-48">
              <div className="pr:text-center">
                <DocumentTextIcon className="pr:w-12 pr:h-12 pr:text-gray-300 pr:mx-auto pr:mb-3" />
                <p className="pr:text-gray-500">
                  {__("No issues found for this category", "prorank-seo")}
                </p>
              </div>
            </div>
          ) : (
            <div className="pr:divide-y pr:divide-gray-200">
              {issues.map((issue) => (
                <IssueDetailRow
                  key={issue.id}
                  issue={issue}
                  onApplyFix={handleApplyFix}
                  onIgnore={onIgnore}
                  isApplyingFix={applyingFixId === issue.id}
                />
              ))}
            </div>
          )}
        </div>

        {/* Pagination */}
        {pagination.pages > 1 && (
          <div className="pr:flex pr:items-center pr:justify-between pr:p-4 pr:border-t pr:border-gray-200 pr:bg-gray-50">
            <Button
              variant="secondary"
              size="sm"
              onClick={() => onPageChange && onPageChange(pagination.page - 1)}
              disabled={pagination.page <= 1}
              className="pr:inline-flex pr:items-center pr:gap-1"
            >
              <ChevronLeftIcon className="pr:w-4 pr:h-4" />
              {__("Previous", "prorank-seo")}
            </Button>
            <span className="pr:text-sm pr:text-gray-600">
              {sprintf(
                __("Page %d of %d", "prorank-seo"),
                pagination.page,
                pagination.pages
              )}
            </span>
            <Button
              variant="secondary"
              size="sm"
              onClick={() => onPageChange && onPageChange(pagination.page + 1)}
              disabled={pagination.page >= pagination.pages}
              className="pr:inline-flex pr:items-center pr:gap-1"
            >
              {__("Next", "prorank-seo")}
              <ChevronRightIcon className="pr:w-4 pr:h-4" />
            </Button>
          </div>
        )}
      </div>
    </>
  );
};

export default CategoryIssuesPanel;
