import React, { useState, useEffect } from "react";
import { ReviewItem, ReviewStatus, UserRole } from "../types/review";
import ReviewWorkflowEngine from "./ReviewWorkflowEngine";

interface ContentReviewDashboardProps {
  siteId: string;
  userId: string;
  userRole: UserRole;
  className?: string;
}

interface DashboardStats {
  totalReviews: number;
  pendingReviews: number;
  approvedToday: number;
  overdueReviews: number;
  avgReviewTime: number;
  completionRate: number;
}

interface FilterOptions {
  status: ReviewStatus | "all";
  priority: "all" | "urgent" | "high" | "medium" | "low";
  contentType: "all" | string;
  dateRange: "today" | "week" | "month" | "all";
}

export const ContentReviewDashboard: React.FC<ContentReviewDashboardProps> = ({
  siteId,
  userId,
  userRole,
  className = "",
}) => {
  const [stats, setStats] = useState<DashboardStats>({
    totalReviews: 0,
    pendingReviews: 0,
    approvedToday: 0,
    overdueReviews: 0,
    avgReviewTime: 0,
    completionRate: 0,
  });

  const [filters, setFilters] = useState<FilterOptions>({
    status: "all",
    priority: "all",
    contentType: "all",
    dateRange: "week",
  });

  const [activeTab, setActiveTab] = useState<
    "overview" | "reviews" | "analytics" | "settings"
  >("overview");
  const [isLoading, setIsLoading] = useState(true);

  // Mock stats data
  useEffect(() => {
    const loadStats = async () => {
      setIsLoading(true);
      // Simulate API call
      await new Promise((resolve) => setTimeout(resolve, 1000));

      setStats({
        totalReviews: 156,
        pendingReviews: 12,
        approvedToday: 8,
        overdueReviews: 3,
        avgReviewTime: 2.5,
        completionRate: 94,
      });
      setIsLoading(false);
    };

    loadStats();
  }, [siteId, filters.dateRange]);

  const getStatColor = (
    value: number,
    type: "good" | "neutral" | "warning" | "danger"
  ) => {
    switch (type) {
      case "good":
        return "text-green-600";
      case "neutral":
        return "text-blue-600";
      case "warning":
        return "text-orange-600";
      case "danger":
        return "text-red-600";
      default:
        return "text-gray-600";
    }
  };

  const renderOverviewTab = () => (
    <div className="space-y-6">
      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">Total Reviews</p>
              <p
                className={`text-3xl font-bold ${getStatColor(
                  stats.totalReviews,
                  "neutral"
                )}`}
              >
                {stats.totalReviews}
              </p>
            </div>
            <div className="h-12 w-12 bg-blue-100 rounded-lg flex items-center justify-center">
              <svg
                className="h-6 w-6 text-blue-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                />
              </svg>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">
                Pending Reviews
              </p>
              <p
                className={`text-3xl font-bold ${getStatColor(
                  stats.pendingReviews,
                  "warning"
                )}`}
              >
                {stats.pendingReviews}
              </p>
            </div>
            <div className="h-12 w-12 bg-orange-100 rounded-lg flex items-center justify-center">
              <svg
                className="h-6 w-6 text-orange-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">
                Approved Today
              </p>
              <p
                className={`text-3xl font-bold ${getStatColor(
                  stats.approvedToday,
                  "good"
                )}`}
              >
                {stats.approvedToday}
              </p>
            </div>
            <div className="h-12 w-12 bg-green-100 rounded-lg flex items-center justify-center">
              <svg
                className="h-6 w-6 text-green-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M5 13l4 4L19 7"
                />
              </svg>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">
                Overdue Reviews
              </p>
              <p
                className={`text-3xl font-bold ${getStatColor(
                  stats.overdueReviews,
                  "danger"
                )}`}
              >
                {stats.overdueReviews}
              </p>
            </div>
            <div className="h-12 w-12 bg-red-100 rounded-lg flex items-center justify-center">
              <svg
                className="h-6 w-6 text-red-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">
                Avg Review Time
              </p>
              <p
                className={`text-3xl font-bold ${getStatColor(
                  stats.avgReviewTime,
                  "neutral"
                )}`}
              >
                {stats.avgReviewTime}h
              </p>
            </div>
            <div className="h-12 w-12 bg-purple-100 rounded-lg flex items-center justify-center">
              <svg
                className="h-6 w-6 text-purple-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M13 10V3L4 14h7v7l9-11h-7z"
                />
              </svg>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm font-medium text-gray-600">
                Completion Rate
              </p>
              <p
                className={`text-3xl font-bold ${getStatColor(
                  stats.completionRate,
                  "good"
                )}`}
              >
                {stats.completionRate}%
              </p>
            </div>
            <div className="h-12 w-12 bg-indigo-100 rounded-lg flex items-center justify-center">
              <svg
                className="h-6 w-6 text-indigo-600"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
                />
              </svg>
            </div>
          </div>
        </div>
      </div>

      {/* Recent Activity */}
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">
          Recent Activity
        </h3>
        <div className="space-y-4">
          {[
            {
              id: 1,
              action: "approved",
              content: "Hero Section Update",
              user: "Content Manager",
              time: "2 hours ago",
              type: "content_update",
            },
            {
              id: 2,
              action: "submitted",
              content: "New FAQ Section",
              user: "Marketing Team",
              time: "4 hours ago",
              type: "content_creation",
            },
            {
              id: 3,
              action: "rejected",
              content: "Pricing Page Changes",
              user: "Legal Team",
              time: "6 hours ago",
              type: "legal_compliance",
            },
          ].map((activity) => (
            <div
              key={activity.id}
              className="flex items-center gap-4 p-3 border border-gray-100 rounded-lg"
            >
              <div
                className={`h-2 w-2 rounded-full ${
                  activity.action === "approved"
                    ? "bg-green-500"
                    : activity.action === "rejected"
                    ? "bg-red-500"
                    : "bg-blue-500"
                }`}
              />
              <div className="flex-1">
                <p className="text-sm text-gray-900">
                  <span className="font-medium">{activity.user}</span>{" "}
                  {activity.action}
                  <span className="font-medium"> {activity.content}</span>
                </p>
                <p className="text-xs text-gray-500">{activity.time}</p>
              </div>
              <span
                className={`px-2 py-1 rounded-full text-xs font-medium ${
                  activity.type === "content_update"
                    ? "bg-blue-100 text-blue-800"
                    : activity.type === "content_creation"
                    ? "bg-green-100 text-green-800"
                    : "bg-orange-100 text-orange-800"
                }`}
              >
                {activity.type.replace("_", " ")}
              </span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );

  const renderFilters = () => (
    <div className="bg-white rounded-lg border border-gray-200 p-4 mb-6">
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Status
          </label>
          <select
            value={filters.status}
            onChange={(e) =>
              setFilters((prev) => ({
                ...prev,
                status: e.target.value as ReviewStatus | "all",
              }))
            }
            className="block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm"
          >
            <option value="all">All Statuses</option>
            <option value="draft">Draft</option>
            <option value="pending_review">Pending Review</option>
            <option value="under_review">Under Review</option>
            <option value="approved">Approved</option>
            <option value="rejected">Rejected</option>
            <option value="published">Published</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Priority
          </label>
          <select
            value={filters.priority}
            onChange={(e) =>
              setFilters((prev) => ({
                ...prev,
                priority: e.target.value as FilterOptions["priority"],
              }))
            }
            className="block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm"
          >
            <option value="all">All Priorities</option>
            <option value="urgent">Urgent</option>
            <option value="high">High</option>
            <option value="medium">Medium</option>
            <option value="low">Low</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Content Type
          </label>
          <select
            value={filters.contentType}
            onChange={(e) =>
              setFilters((prev) => ({ ...prev, contentType: e.target.value }))
            }
            className="block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm"
          >
            <option value="all">All Types</option>
            <option value="hero_section">Hero Section</option>
            <option value="cta_section">CTA Section</option>
            <option value="pricing_section">Pricing Section</option>
            <option value="features_section">Features Section</option>
            <option value="faq_section">FAQ Section</option>
            <option value="testimonial_section">Testimonial Section</option>
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Date Range
          </label>
          <select
            value={filters.dateRange}
            onChange={(e) =>
              setFilters((prev) => ({
                ...prev,
                dateRange: e.target.value as FilterOptions["dateRange"],
              }))
            }
            className="block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 text-sm"
          >
            <option value="today">Today</option>
            <option value="week">This Week</option>
            <option value="month">This Month</option>
            <option value="all">All Time</option>
          </select>
        </div>
      </div>
    </div>
  );

  const renderAnalyticsTab = () => (
    <div className="space-y-6">
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">
          Review Performance Metrics
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <h4 className="font-medium text-gray-900 mb-3">
              Review Volume by Type
            </h4>
            <div className="space-y-2">
              {[
                { type: "Hero Section", count: 45, percentage: 28 },
                { type: "CTA Section", count: 32, percentage: 20 },
                { type: "Features Section", count: 28, percentage: 18 },
                { type: "Pricing Section", count: 25, percentage: 16 },
                { type: "FAQ Section", count: 15, percentage: 10 },
                { type: "Testimonials", count: 11, percentage: 8 },
              ].map((item) => (
                <div
                  key={item.type}
                  className="flex items-center justify-between"
                >
                  <span className="text-sm text-gray-600">{item.type}</span>
                  <div className="flex items-center gap-2">
                    <div className="w-24 bg-gray-200 rounded-full h-2">
                      <div
                        className="bg-blue-600 h-2 rounded-full"
                        style={{ width: `${item.percentage}%` }}
                      />
                    </div>
                    <span className="text-sm font-medium text-gray-900 w-8">
                      {item.count}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div>
            <h4 className="font-medium text-gray-900 mb-3">
              Average Review Time by Stage
            </h4>
            <div className="space-y-2">
              {[
                { stage: "Editor Review", time: "1.2 hours", status: "good" },
                {
                  stage: "Content Review",
                  time: "2.8 hours",
                  status: "neutral",
                },
                { stage: "Legal Review", time: "4.5 hours", status: "warning" },
                { stage: "Final Approval", time: "0.8 hours", status: "good" },
              ].map((item) => (
                <div
                  key={item.stage}
                  className="flex items-center justify-between"
                >
                  <span className="text-sm text-gray-600">{item.stage}</span>
                  <span
                    className={`text-sm font-medium ${getStatColor(
                      0,
                      item.status as any
                    )}`}
                  >
                    {item.time}
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">
          Reviewer Performance
        </h3>
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Reviewer
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Reviews Completed
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Avg Time
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Approval Rate
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {[
                {
                  name: "Content Manager",
                  completed: 24,
                  avgTime: "2.1h",
                  approvalRate: 95,
                },
                {
                  name: "Marketing Lead",
                  completed: 18,
                  avgTime: "1.8h",
                  approvalRate: 92,
                },
                {
                  name: "Legal Reviewer",
                  completed: 12,
                  avgTime: "4.2h",
                  approvalRate: 88,
                },
                {
                  name: "SEO Specialist",
                  completed: 15,
                  avgTime: "1.5h",
                  approvalRate: 98,
                },
              ].map((reviewer) => (
                <tr key={reviewer.name}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                    {reviewer.name}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {reviewer.completed}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {reviewer.avgTime}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {reviewer.approvalRate}%
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );

  if (isLoading) {
    return (
      <div className={`content-review-dashboard ${className}`}>
        <div className="flex items-center justify-center p-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <span className="ml-2 text-gray-600">Loading dashboard...</span>
        </div>
      </div>
    );
  }

  return (
    <div className={`content-review-dashboard ${className}`}>
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">
          Content Review Dashboard
        </h1>
        <p className="mt-1 text-sm text-gray-600">
          Manage and monitor content review processes across your AgentC sites
        </p>
      </div>

      {/* Navigation Tabs */}
      <div className="border-b border-gray-200 mb-6">
        <nav className="-mb-px flex space-x-8">
          {[
            { id: "overview", label: "Overview", icon: "📊" },
            { id: "reviews", label: "Reviews", icon: "📝" },
            { id: "analytics", label: "Analytics", icon: "📈" },
            { id: "settings", label: "Settings", icon: "⚙️" },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as typeof activeTab)}
              className={`flex items-center gap-2 py-2 px-1 border-b-2 font-medium text-sm ${
                activeTab === tab.id
                  ? "border-blue-500 text-blue-600"
                  : "border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
              }`}
            >
              <span>{tab.icon}</span>
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === "overview" && renderOverviewTab()}

      {activeTab === "reviews" && (
        <div>
          {renderFilters()}
          <ReviewWorkflowEngine
            siteId={siteId}
            userId={userId}
            userRole={userRole}
          />
        </div>
      )}

      {activeTab === "analytics" && renderAnalyticsTab()}

      {activeTab === "settings" && (
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">
            Review Process Settings
          </h3>
          <p className="text-gray-600">
            Settings configuration will be implemented in future iterations.
          </p>
        </div>
      )}
    </div>
  );
};

export default ContentReviewDashboard;
