import React, { useState, useEffect, useCallback } from "react";
import {
  ReviewItem,
  ReviewWorkflow,
  ReviewStatus,
  ReviewType,
  ContentType,
  UserRole,
  ReviewChecklistItem,
  ReviewAction,
  ReviewStage,
} from "../types/review";

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

interface WorkflowState {
  workflows: ReviewWorkflow[];
  activeReviews: ReviewItem[];
  pendingActions: ReviewAction[];
  isLoading: boolean;
  error: string | null;
}

export const ReviewWorkflowEngine: React.FC<ReviewWorkflowEngineProps> = ({
  siteId,
  userId,
  userRole,
  className = "",
}) => {
  const [state, setState] = useState<WorkflowState>({
    workflows: [],
    activeReviews: [],
    pendingActions: [],
    isLoading: false,
    error: null,
  });

  // Mock workflows for demo
  const mockWorkflows: ReviewWorkflow[] = [
    {
      id: "standard-content-review",
      name: "Standard Content Review",
      description: "Standard review process for content updates",
      contentTypes: ["hero_section", "cta_section", "features_section"],
      reviewTypes: ["content_update", "content_creation"],
      stages: [
        {
          id: "editor-review",
          name: "Editor Review",
          description: "Initial content review by editor",
          order: 1,
          requiredRoles: ["editor"],
          minimumApprovers: 1,
          requiredChecklist: ["content-quality", "brand-guidelines"],
          stageSLAHours: 24,
          autoApprove: false,
          onEntry: [],
          onExit: [],
          onTimeout: [],
          onApproval: [],
          onRejection: [],
        },
        {
          id: "reviewer-approval",
          name: "Reviewer Approval",
          description: "Final approval by content reviewer",
          order: 2,
          requiredRoles: ["reviewer", "approver"],
          minimumApprovers: 1,
          requiredChecklist: ["seo-check", "accessibility-check"],
          stageSLAHours: 48,
          autoApprove: false,
          onEntry: [],
          onExit: [],
          onTimeout: [],
          onApproval: [],
          onRejection: [],
        },
      ],
      currentStage: 0,
      autoAssignment: true,
      parallelReview: false,
      requireAllApprovals: true,
      escalationEnabled: true,
      escalationThresholdHours: 72,
      slaHours: 72,
      reminderIntervals: [24, 48],
      active: true,
      version: 1,
      createdBy: "system",
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  ];

  // Mock active reviews
  const mockActiveReviews: ReviewItem[] = [
    {
      id: "review-001",
      title: "Hero Section Update",
      description: "Update hero section content for summer campaign",
      contentType: "hero_section",
      reviewType: "content_update",
      status: "under_review",
      priority: "medium",
      contentId: "hero-main",
      siteId,
      version: 2,
      currentContent: {
        title: "Welcome to AgentC",
        subtitle: "Build amazing websites with AI",
        ctaText: "Get Started",
      },
      proposedChanges: {
        title: "Summer Sale - 50% Off AgentC",
        subtitle: "Build amazing websites with AI - Limited Time Offer",
        ctaText: "Start Building Now",
      },
      changesSummary: "Updated messaging for summer campaign promotion",
      submittedBy: "content-manager",
      submittedAt: new Date(Date.now() - 86400000), // 1 day ago
      assignedTo: userId,
      assignedAt: new Date(Date.now() - 43200000), // 12 hours ago
      reviewNotes: "",
      approvalNotes: "",
      reviewChecklist: [
        {
          id: "content-quality",
          category: "Content Quality",
          requirement: "Content follows brand voice and tone guidelines",
          checked: false,
          required: true,
        },
        {
          id: "brand-guidelines",
          category: "Brand Guidelines",
          requirement: "Content adheres to brand messaging standards",
          checked: false,
          required: true,
        },
        {
          id: "seo-check",
          category: "SEO",
          requirement: "Content is optimized for search engines",
          checked: false,
          required: true,
        },
        {
          id: "accessibility-check",
          category: "Accessibility",
          requirement: "Content meets accessibility standards",
          checked: false,
          required: false,
        },
      ],
      requiresLegalReview: false,
      requiresSEOReview: true,
      requiresAccessibilityReview: false,
      estimatedReviewTime: 60,
      deadlineDate: new Date(Date.now() + 172800000), // 2 days from now
      tags: ["hero", "campaign", "summer-sale"],
      workflowStage: "editor-review",
      nextActionRequired: "Complete review checklist and approve/reject",
      escalationLevel: 0,
      createdAt: new Date(Date.now() - 86400000),
      updatedAt: new Date(Date.now() - 43200000),
    },
  ];

  const loadWorkflows = useCallback(async () => {
    setState((prev) => ({ ...prev, isLoading: true, error: null }));

    try {
      // Simulate API call
      await new Promise((resolve) => setTimeout(resolve, 1000));

      setState((prev) => ({
        ...prev,
        workflows: mockWorkflows,
        activeReviews: mockActiveReviews,
        isLoading: false,
      }));
    } catch (error) {
      setState((prev) => ({
        ...prev,
        isLoading: false,
        error:
          error instanceof Error ? error.message : "Failed to load workflows",
      }));
    }
  }, [siteId]);

  const handleApproveReview = useCallback(
    async (reviewId: string, notes: string) => {
      try {
        setState((prev) => ({
          ...prev,
          activeReviews: prev.activeReviews.map((review) =>
            review.id === reviewId
              ? {
                  ...review,
                  status: "approved" as ReviewStatus,
                  approvalNotes: notes,
                  reviewedBy: userId,
                  reviewedAt: new Date(),
                  approvedBy: userId,
                  approvedAt: new Date(),
                }
              : review
          ),
        }));
      } catch (error) {
        setState((prev) => ({
          ...prev,
          error:
            error instanceof Error ? error.message : "Failed to approve review",
        }));
      }
    },
    [userId]
  );

  const handleRejectReview = useCallback(
    async (reviewId: string, reason: string) => {
      try {
        setState((prev) => ({
          ...prev,
          activeReviews: prev.activeReviews.map((review) =>
            review.id === reviewId
              ? {
                  ...review,
                  status: "rejected" as ReviewStatus,
                  rejectionReason: reason,
                  reviewedBy: userId,
                  reviewedAt: new Date(),
                }
              : review
          ),
        }));
      } catch (error) {
        setState((prev) => ({
          ...prev,
          error:
            error instanceof Error ? error.message : "Failed to reject review",
        }));
      }
    },
    [userId]
  );

  const handleChecklistUpdate = useCallback(
    (reviewId: string, checklistItemId: string, checked: boolean) => {
      setState((prev) => ({
        ...prev,
        activeReviews: prev.activeReviews.map((review) =>
          review.id === reviewId
            ? {
                ...review,
                reviewChecklist: review.reviewChecklist.map((item) =>
                  item.id === checklistItemId
                    ? {
                        ...item,
                        checked,
                        checkedBy: checked ? userId : undefined,
                        checkedAt: checked ? new Date() : undefined,
                      }
                    : item
                ),
              }
            : review
        ),
      }));
    },
    [userId]
  );

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

  if (state.isLoading) {
    return (
      <div className={`review-workflow-engine ${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 review workflows...
          </span>
        </div>
      </div>
    );
  }

  if (state.error) {
    return (
      <div className={`review-workflow-engine ${className}`}>
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex">
            <div className="flex-shrink-0">
              <svg
                className="h-5 w-5 text-red-400"
                viewBox="0 0 20 20"
                fill="currentColor"
              >
                <path
                  fillRule="evenodd"
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                  clipRule="evenodd"
                />
              </svg>
            </div>
            <div className="ml-3">
              <h3 className="text-sm font-medium text-red-800">Error</h3>
              <p className="mt-1 text-sm text-red-700">{state.error}</p>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`review-workflow-engine ${className}`}>
      <div className="space-y-6">
        {/* Workflow Status Overview */}
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">
            Review Workflow Status
          </h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="bg-blue-50 rounded-lg p-4">
              <h3 className="text-sm font-medium text-blue-900">
                Active Reviews
              </h3>
              <p className="text-2xl font-bold text-blue-600">
                {
                  state.activeReviews.filter((r) =>
                    ["under_review", "pending_review"].includes(r.status)
                  ).length
                }
              </p>
            </div>
            <div className="bg-green-50 rounded-lg p-4">
              <h3 className="text-sm font-medium text-green-900">
                Approved Today
              </h3>
              <p className="text-2xl font-bold text-green-600">
                {
                  state.activeReviews.filter(
                    (r) =>
                      r.status === "approved" &&
                      r.approvedAt &&
                      new Date(r.approvedAt).toDateString() ===
                        new Date().toDateString()
                  ).length
                }
              </p>
            </div>
            <div className="bg-orange-50 rounded-lg p-4">
              <h3 className="text-sm font-medium text-orange-900">Overdue</h3>
              <p className="text-2xl font-bold text-orange-600">
                {
                  state.activeReviews.filter(
                    (r) =>
                      r.deadlineDate &&
                      new Date(r.deadlineDate) < new Date() &&
                      !["approved", "published", "archived"].includes(r.status)
                  ).length
                }
              </p>
            </div>
          </div>
        </div>

        {/* Active Reviews List */}
        <div className="bg-white rounded-lg border border-gray-200">
          <div className="p-6 border-b border-gray-200">
            <h2 className="text-lg font-semibold text-gray-900">
              Active Reviews
            </h2>
          </div>
          <div className="divide-y divide-gray-200">
            {state.activeReviews.map((review) => (
              <ReviewItemCard
                key={review.id}
                review={review}
                currentUserId={userId}
                currentUserRole={userRole}
                onApprove={handleApproveReview}
                onReject={handleRejectReview}
                onChecklistUpdate={handleChecklistUpdate}
              />
            ))}
          </div>
        </div>

        {/* Workflow Configuration */}
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">
            Configured Workflows
          </h2>
          <div className="space-y-4">
            {state.workflows.map((workflow) => (
              <div
                key={workflow.id}
                className="border border-gray-100 rounded-lg p-4"
              >
                <div className="flex items-center justify-between mb-2">
                  <h3 className="font-medium text-gray-900">{workflow.name}</h3>
                  <span
                    className={`px-2 py-1 rounded-full text-xs font-medium ${
                      workflow.active
                        ? "bg-green-100 text-green-800"
                        : "bg-gray-100 text-gray-800"
                    }`}
                  >
                    {workflow.active ? "Active" : "Inactive"}
                  </span>
                </div>
                <p className="text-sm text-gray-600 mb-3">
                  {workflow.description}
                </p>
                <div className="flex flex-wrap gap-2">
                  <div className="text-xs text-gray-500">
                    Content Types: {workflow.contentTypes.join(", ")}
                  </div>
                  <div className="text-xs text-gray-500">
                    SLA: {workflow.slaHours}h
                  </div>
                  <div className="text-xs text-gray-500">
                    Stages: {workflow.stages.length}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

interface ReviewItemCardProps {
  review: ReviewItem;
  currentUserId: string;
  currentUserRole: UserRole;
  onApprove: (reviewId: string, notes: string) => void;
  onReject: (reviewId: string, reason: string) => void;
  onChecklistUpdate: (
    reviewId: string,
    checklistItemId: string,
    checked: boolean
  ) => void;
}

const ReviewItemCard: React.FC<ReviewItemCardProps> = ({
  review,
  currentUserId,
  currentUserRole,
  onApprove,
  onReject,
  onChecklistUpdate,
}) => {
  const [showDetails, setShowDetails] = useState(false);
  const [approvalNotes, setApprovalNotes] = useState("");
  const [rejectionReason, setRejectionReason] = useState("");

  const getStatusColor = (status: ReviewStatus) => {
    switch (status) {
      case "pending_review":
        return "bg-yellow-100 text-yellow-800";
      case "under_review":
        return "bg-blue-100 text-blue-800";
      case "approved":
        return "bg-green-100 text-green-800";
      case "rejected":
        return "bg-red-100 text-red-800";
      case "published":
        return "bg-purple-100 text-purple-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case "urgent":
        return "bg-red-100 text-red-800";
      case "high":
        return "bg-orange-100 text-orange-800";
      case "medium":
        return "bg-yellow-100 text-yellow-800";
      case "low":
        return "bg-green-100 text-green-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  const canUserReview = (userRole: UserRole, reviewStage: string) => {
    // Simplified permission check
    if (userRole === "admin" || userRole === "super_admin") return true;
    if (reviewStage === "editor-review" && userRole === "editor") return true;
    if (
      reviewStage === "reviewer-approval" &&
      (userRole === "reviewer" || userRole === "approver")
    )
      return true;
    return false;
  };

  const requiredItemsCompleted = review.reviewChecklist
    .filter((item) => item.required)
    .every((item) => item.checked);

  return (
    <div className="p-6">
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-2">
            <h3 className="text-lg font-medium text-gray-900">
              {review.title}
            </h3>
            <span
              className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(
                review.status
              )}`}
            >
              {review.status.replace("_", " ")}
            </span>
            <span
              className={`px-2 py-1 rounded-full text-xs font-medium ${getPriorityColor(
                review.priority
              )}`}
            >
              {review.priority}
            </span>
          </div>
          <p className="text-gray-600 mb-3">{review.description}</p>
          <div className="flex flex-wrap gap-4 text-sm text-gray-500">
            <span>Type: {review.contentType.replace("_", " ")}</span>
            <span>Version: {review.version}</span>
            <span>
              Submitted: {new Date(review.submittedAt).toLocaleDateString()}
            </span>
            {review.deadlineDate && (
              <span
                className={`${
                  new Date(review.deadlineDate) < new Date()
                    ? "text-red-600 font-medium"
                    : ""
                }`}
              >
                Deadline: {new Date(review.deadlineDate).toLocaleDateString()}
              </span>
            )}
          </div>
        </div>
        <button
          onClick={() => setShowDetails(!showDetails)}
          className="text-blue-600 hover:text-blue-700 text-sm font-medium"
        >
          {showDetails ? "Hide Details" : "Show Details"}
        </button>
      </div>

      {showDetails && (
        <div className="mt-6 border-t border-gray-200 pt-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Changes Preview */}
            <div>
              <h4 className="font-medium text-gray-900 mb-3">
                Proposed Changes
              </h4>
              <div className="bg-gray-50 rounded-lg p-4">
                <div className="space-y-2">
                  <div>
                    <span className="text-sm font-medium text-gray-600">
                      Changes Summary:
                    </span>
                    <p className="text-sm text-gray-900">
                      {review.changesSummary}
                    </p>
                  </div>
                  <div>
                    <span className="text-sm font-medium text-gray-600">
                      Proposed Content:
                    </span>
                    <pre className="text-sm text-gray-900 whitespace-pre-wrap">
                      {JSON.stringify(review.proposedChanges, null, 2)}
                    </pre>
                  </div>
                </div>
              </div>
            </div>

            {/* Review Checklist */}
            <div>
              <h4 className="font-medium text-gray-900 mb-3">
                Review Checklist
              </h4>
              <div className="space-y-3">
                {review.reviewChecklist.map((item) => (
                  <div key={item.id} className="flex items-start gap-3">
                    <input
                      type="checkbox"
                      id={`checklist-${item.id}`}
                      checked={item.checked}
                      onChange={(e) =>
                        onChecklistUpdate(review.id, item.id, e.target.checked)
                      }
                      disabled={
                        !canUserReview(currentUserRole, review.workflowStage)
                      }
                      className="mt-1 h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                    />
                    <div className="flex-1">
                      <label
                        htmlFor={`checklist-${item.id}`}
                        className={`text-sm ${
                          item.required ? "font-medium" : ""
                        } text-gray-900`}
                      >
                        {item.requirement}
                        {item.required && (
                          <span className="text-red-500 ml-1">*</span>
                        )}
                      </label>
                      <div className="text-xs text-gray-500">
                        {item.category}
                      </div>
                      {item.checked && item.checkedBy && (
                        <div className="text-xs text-green-600">
                          ✓ Checked by {item.checkedBy} on{" "}
                          {item.checkedAt &&
                            new Date(item.checkedAt).toLocaleDateString()}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Review Actions */}
          {canUserReview(currentUserRole, review.workflowStage) &&
            review.status === "under_review" && (
              <div className="mt-6 border-t border-gray-200 pt-6">
                <h4 className="font-medium text-gray-900 mb-3">
                  Review Actions
                </h4>
                <div className="space-y-4">
                  <div>
                    <label
                      htmlFor="approval-notes"
                      className="block text-sm font-medium text-gray-700 mb-1"
                    >
                      Review Notes
                    </label>
                    <textarea
                      id="approval-notes"
                      value={approvalNotes}
                      onChange={(e) => setApprovalNotes(e.target.value)}
                      rows={3}
                      className="block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"
                      placeholder="Add any notes about this review..."
                    />
                  </div>
                  <div className="flex gap-3">
                    <button
                      onClick={() => onApprove(review.id, approvalNotes)}
                      disabled={!requiredItemsCompleted}
                      className={`px-4 py-2 rounded-md text-sm font-medium ${
                        requiredItemsCompleted
                          ? "bg-green-600 text-white hover:bg-green-700"
                          : "bg-gray-300 text-gray-500 cursor-not-allowed"
                      }`}
                    >
                      Approve
                    </button>
                    <button
                      onClick={() => {
                        const reason = prompt(
                          "Please provide a reason for rejection:"
                        );
                        if (reason) {
                          onReject(review.id, reason);
                        }
                      }}
                      className="px-4 py-2 bg-red-600 text-white rounded-md text-sm font-medium hover:bg-red-700"
                    >
                      Reject
                    </button>
                  </div>
                  {!requiredItemsCompleted && (
                    <p className="text-sm text-orange-600">
                      Please complete all required checklist items before
                      approving.
                    </p>
                  )}
                </div>
              </div>
            )}
        </div>
      )}
    </div>
  );
};

export default ReviewWorkflowEngine;
