import React, { useState, useEffect } from "react";
import {
  ContentCalendar,
  CalendarEntry,
  ReviewPriority,
} from "../types/review";

interface ContentCalendarProps {
  siteId: string;
  className?: string;
}

interface CalendarView {
  month: number;
  year: number;
  selectedDate: Date | null;
}

export const ContentCalendarComponent: React.FC<ContentCalendarProps> = ({
  siteId,
  className = "",
}) => {
  const [calendar, setCalendar] = useState<ContentCalendar | null>(null);
  const [view, setView] = useState<CalendarView>({
    month: new Date().getMonth(),
    year: new Date().getFullYear(),
    selectedDate: null,
  });
  const [isLoading, setIsLoading] = useState(true);
  const [showEventModal, setShowEventModal] = useState(false);

  const mockCalendar: ContentCalendar = {
    id: "calendar-main",
    name: "Main Content Calendar",
    description: "Primary calendar for content review scheduling",
    siteId,
    entries: [
      {
        id: "entry-1",
        title: "Hero Section Review",
        description: "Quarterly review of hero section content",
        type: "review",
        startDate: new Date(2024, 2, 15),
        allDay: true,
        recurring: false,
        assignedTo: ["content-manager", "marketing-lead"],
        createdBy: "admin",
        status: "scheduled",
        priority: "medium",
        tags: ["hero", "quarterly"],
        estimatedHours: 2,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        id: "entry-2",
        title: "Pricing Update Publication",
        description: "Publish approved pricing changes",
        type: "publication",
        startDate: new Date(2024, 2, 20),
        allDay: false,
        recurring: false,
        assignedTo: ["content-manager"],
        createdBy: "admin",
        status: "scheduled",
        priority: "high",
        tags: ["pricing", "publication"],
        estimatedHours: 1,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        id: "entry-3",
        title: "Content Audit",
        description: "Monthly content audit and cleanup",
        type: "audit",
        startDate: new Date(2024, 2, 25),
        allDay: true,
        recurring: true,
        recurrenceRule: "FREQ=MONTHLY;BYMONTHDAY=25",
        assignedTo: ["content-manager", "seo-specialist"],
        createdBy: "admin",
        status: "scheduled",
        priority: "medium",
        tags: ["audit", "monthly"],
        estimatedHours: 4,
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ],
    timezone: "UTC",
    workingDays: [1, 2, 3, 4, 5], // Monday to Friday
    workingHours: {
      start: "09:00",
      end: "17:00",
    },
    createdBy: "admin",
    createdAt: new Date(),
    updatedAt: new Date(),
  };

  useEffect(() => {
    const loadCalendar = async () => {
      setIsLoading(true);
      // Simulate API call
      await new Promise((resolve) => setTimeout(resolve, 1000));
      setCalendar(mockCalendar);
      setIsLoading(false);
    };

    loadCalendar();
  }, [siteId]);

  const getDaysInMonth = (month: number, year: number) => {
    return new Date(year, month + 1, 0).getDate();
  };

  const getFirstDayOfMonth = (month: number, year: number) => {
    return new Date(year, month, 1).getDay();
  };

  const getEventsForDate = (date: Date): CalendarEntry[] => {
    if (!calendar) return [];

    return calendar.entries.filter((entry) => {
      const entryDate = new Date(entry.startDate);
      return (
        entryDate.getDate() === date.getDate() &&
        entryDate.getMonth() === date.getMonth() &&
        entryDate.getFullYear() === date.getFullYear()
      );
    });
  };

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

  const getTypeIcon = (type: string) => {
    switch (type) {
      case "review":
        return "📝";
      case "publication":
        return "🚀";
      case "expiration":
        return "⏰";
      case "audit":
        return "🔍";
      case "campaign":
        return "📢";
      default:
        return "📅";
    }
  };

  const navigateMonth = (direction: "prev" | "next") => {
    setView((prev) => {
      const newMonth = direction === "prev" ? prev.month - 1 : prev.month + 1;
      const newYear =
        newMonth < 0
          ? prev.year - 1
          : newMonth > 11
          ? prev.year + 1
          : prev.year;
      const adjustedMonth = newMonth < 0 ? 11 : newMonth > 11 ? 0 : newMonth;

      return {
        ...prev,
        month: adjustedMonth,
        year: newYear,
      };
    });
  };

  const renderCalendarGrid = () => {
    const daysInMonth = getDaysInMonth(view.month, view.year);
    const firstDay = getFirstDayOfMonth(view.month, view.year);
    const days = [];
    const monthNames = [
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August",
      "September",
      "October",
      "November",
      "December",
    ];

    // Add empty cells for days before the first day of the month
    for (let i = 0; i < firstDay; i++) {
      days.push(<div key={`empty-${i}`} className="p-2 h-24"></div>);
    }

    // Add cells for each day of the month
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(view.year, view.month, day);
      const events = getEventsForDate(date);
      const isToday = new Date().toDateString() === date.toDateString();
      const isSelected =
        view.selectedDate?.toDateString() === date.toDateString();

      days.push(
        <div
          key={day}
          className={`p-2 h-24 border border-gray-200 cursor-pointer hover:bg-gray-50 ${
            isToday ? "bg-blue-50 border-blue-300" : ""
          } ${isSelected ? "bg-blue-100 border-blue-500" : ""}`}
          onClick={() => setView((prev) => ({ ...prev, selectedDate: date }))}
        >
          <div className="flex justify-between items-start">
            <span
              className={`text-sm ${
                isToday ? "font-bold text-blue-600" : "text-gray-700"
              }`}
            >
              {day}
            </span>
            {events.length > 0 && (
              <span className="text-xs bg-blue-100 text-blue-800 px-1 rounded">
                {events.length}
              </span>
            )}
          </div>
          <div className="mt-1 space-y-1">
            {events.slice(0, 2).map((event) => (
              <div
                key={event.id}
                className="text-xs p-1 rounded bg-gray-100 text-gray-700 truncate"
                title={event.title}
              >
                <span className="mr-1">{getTypeIcon(event.type)}</span>
                {event.title}
              </div>
            ))}
            {events.length > 2 && (
              <div className="text-xs text-gray-500">
                +{events.length - 2} more
              </div>
            )}
          </div>
        </div>
      );
    }

    return (
      <div className="bg-white rounded-lg border border-gray-200">
        <div className="p-4 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <h2 className="text-lg font-semibold text-gray-900">
              {monthNames[view.month]} {view.year}
            </h2>
            <div className="flex gap-2">
              <button
                onClick={() => navigateMonth("prev")}
                className="p-2 text-gray-400 hover:text-gray-600"
              >
                <svg
                  className="h-5 w-5"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M15 19l-7-7 7-7"
                  />
                </svg>
              </button>
              <button
                onClick={() =>
                  setView((prev) => ({
                    ...prev,
                    month: new Date().getMonth(),
                    year: new Date().getFullYear(),
                  }))
                }
                className="px-3 py-1 text-sm text-blue-600 hover:text-blue-700"
              >
                Today
              </button>
              <button
                onClick={() => navigateMonth("next")}
                className="p-2 text-gray-400 hover:text-gray-600"
              >
                <svg
                  className="h-5 w-5"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M9 5l7 7-7 7"
                  />
                </svg>
              </button>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-7 gap-0">
          {["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day) => (
            <div
              key={day}
              className="p-3 text-center text-sm font-medium text-gray-500 border-b border-gray-200"
            >
              {day}
            </div>
          ))}
          {days}
        </div>
      </div>
    );
  };

  const renderSelectedDateEvents = () => {
    if (!view.selectedDate) return null;

    const events = getEventsForDate(view.selectedDate);
    const dateStr = view.selectedDate.toLocaleDateString();

    return (
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-lg font-semibold text-gray-900">
            Events for {dateStr}
          </h3>
          <button
            onClick={() => setShowEventModal(true)}
            className="px-3 py-1 bg-blue-600 text-white rounded-md text-sm hover:bg-blue-700"
          >
            Add Event
          </button>
        </div>

        {events.length === 0 ? (
          <p className="text-gray-500 text-center py-4">
            No events scheduled for this date
          </p>
        ) : (
          <div className="space-y-3">
            {events.map((event) => (
              <div
                key={event.id}
                className="border border-gray-200 rounded-lg p-4"
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-lg">{getTypeIcon(event.type)}</span>
                      <h4 className="font-medium text-gray-900">
                        {event.title}
                      </h4>
                      <span
                        className={`w-2 h-2 rounded-full ${getPriorityColor(
                          event.priority
                        )}`}
                      />
                    </div>
                    <p className="text-sm text-gray-600 mb-2">
                      {event.description}
                    </p>
                    <div className="flex flex-wrap gap-4 text-xs text-gray-500">
                      <span>Type: {event.type}</span>
                      <span>Priority: {event.priority}</span>
                      <span>Estimated: {event.estimatedHours}h</span>
                      <span>Assigned: {event.assignedTo.length} people</span>
                    </div>
                    {event.tags.length > 0 && (
                      <div className="flex flex-wrap gap-1 mt-2">
                        {event.tags.map((tag) => (
                          <span
                            key={tag}
                            className="px-2 py-1 bg-gray-100 text-gray-600 rounded-full text-xs"
                          >
                            {tag}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                  <div className="flex gap-2">
                    <button className="text-blue-600 hover:text-blue-700 text-sm">
                      Edit
                    </button>
                    <button className="text-red-600 hover:text-red-700 text-sm">
                      Delete
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    );
  };

  if (isLoading) {
    return (
      <div className={`content-calendar ${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 calendar...</span>
        </div>
      </div>
    );
  }

  return (
    <div className={`content-calendar ${className}`}>
      <div className="space-y-6">
        {/* Calendar Header */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">
              Content Calendar
            </h1>
            <p className="mt-1 text-sm text-gray-600">
              Schedule and track content review activities
            </p>
          </div>
          <button
            onClick={() => setShowEventModal(true)}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            Add Event
          </button>
        </div>

        {/* Calendar Stats */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-blue-100 rounded-lg">
                <span className="text-lg">📝</span>
              </div>
              <div>
                <p className="text-sm text-gray-600">Reviews</p>
                <p className="text-lg font-semibold text-gray-900">
                  {calendar?.entries.filter((e) => e.type === "review")
                    .length || 0}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-green-100 rounded-lg">
                <span className="text-lg">🚀</span>
              </div>
              <div>
                <p className="text-sm text-gray-600">Publications</p>
                <p className="text-lg font-semibold text-gray-900">
                  {calendar?.entries.filter((e) => e.type === "publication")
                    .length || 0}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-orange-100 rounded-lg">
                <span className="text-lg">🔍</span>
              </div>
              <div>
                <p className="text-sm text-gray-600">Audits</p>
                <p className="text-lg font-semibold text-gray-900">
                  {calendar?.entries.filter((e) => e.type === "audit").length ||
                    0}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-lg border border-gray-200 p-4">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-purple-100 rounded-lg">
                <span className="text-lg">📢</span>
              </div>
              <div>
                <p className="text-sm text-gray-600">Campaigns</p>
                <p className="text-lg font-semibold text-gray-900">
                  {calendar?.entries.filter((e) => e.type === "campaign")
                    .length || 0}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Calendar Grid */}
          <div className="lg:col-span-2">{renderCalendarGrid()}</div>

          {/* Event Details Sidebar */}
          <div className="space-y-6">
            {renderSelectedDateEvents()}

            {/* Upcoming Events */}
            <div className="bg-white rounded-lg border border-gray-200 p-6">
              <h3 className="text-lg font-semibold text-gray-900 mb-4">
                Upcoming Events
              </h3>
              <div className="space-y-3">
                {calendar?.entries
                  .filter((entry) => new Date(entry.startDate) > new Date())
                  .sort(
                    (a, b) =>
                      new Date(a.startDate).getTime() -
                      new Date(b.startDate).getTime()
                  )
                  .slice(0, 5)
                  .map((event) => (
                    <div
                      key={event.id}
                      className="flex items-center gap-3 p-2 rounded-lg hover:bg-gray-50"
                    >
                      <span className="text-lg">{getTypeIcon(event.type)}</span>
                      <div className="flex-1">
                        <p className="text-sm font-medium text-gray-900">
                          {event.title}
                        </p>
                        <p className="text-xs text-gray-500">
                          {new Date(event.startDate).toLocaleDateString()}
                        </p>
                      </div>
                      <span
                        className={`w-2 h-2 rounded-full ${getPriorityColor(
                          event.priority
                        )}`}
                      />
                    </div>
                  ))}
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Event Modal Placeholder */}
      {showEventModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h3 className="text-lg font-semibold text-gray-900 mb-4">
              Add New Event
            </h3>
            <p className="text-gray-600 mb-4">
              Event creation form will be implemented in future iterations.
            </p>
            <button
              onClick={() => setShowEventModal(false)}
              className="px-4 py-2 bg-gray-600 text-white rounded-md hover:bg-gray-700"
            >
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default ContentCalendarComponent;
