import { useState, useMemo, useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useChannels } from "../hooks/useChannels";
import { useCalendarPosts, generateCalendarDays } from "../hooks/useCalendarPosts";
import type { EnrichedCalendarPost } from "../hooks/useCalendarPosts";
import CalendarGrid from "../components/calendar/CalendarGrid";
import PostDetailPanel from "../components/calendar/PostDetailPanel";
import { PLATFORM_ICONS, STATUS_STYLES } from "../components/shared";
import { viralySsoUrl } from "../utils/sso";
import clsx from "clsx";

interface Props {
  onNavigate?: (tab: string) => void;
  onCreatePost?: (date?: string) => void;
}

const MONTH_NAMES = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December",
];

const STATUS_FILTER_OPTIONS = [
  { key: "Scheduled", label: "Scheduled", dot: "vr-bg-blue-500" },
  { key: "Published", label: "Published", dot: "vr-bg-emerald-500" },
  { key: "Draft", label: "Draft", dot: "vr-bg-gray-400" },
  { key: "Failed", label: "Failed", dot: "vr-bg-red-500" },
];

export default function Calendar({ onNavigate, onCreatePost }: Props) {
  const now = new Date();
  const [year, setYear] = useState(now.getFullYear());
  const [month, setMonth] = useState(now.getMonth());
  const [channelFilter, setChannelFilter] = useState<string | null>(null);
  const [statusFilters, setStatusFilters] = useState<string[]>([]);
  const [selectedPost, setSelectedPost] = useState<EnrichedCalendarPost | null>(null);

  const queryClient = useQueryClient();
  const { channels, isLoading: channelsLoading } = useChannels();
  const activeChannels = channels.filter((ch) => ch.status === "Active");

  const handlePostDeleted = () => {
    setSelectedPost(null);
    queryClient.invalidateQueries({ queryKey: ["calendar-posts"] });
  };

  // Show success confirmation if redirected from Compose/InlineShare
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  useEffect(() => {
    const msg = sessionStorage.getItem("viraly_post_success");
    if (msg) {
      setSuccessMsg(msg);
      sessionStorage.removeItem("viraly_post_success");
      // Auto-dismiss after 5 seconds
      setTimeout(() => setSuccessMsg(null), 5000);
    }
  }, []);

  const { posts, postsByDate, total, isLoading, hasError } = useCalendarPosts(
    year, month, channels, channelFilter, statusFilters
  );

  const days = useMemo(
    () => generateCalendarDays(year, month, postsByDate),
    [year, month, postsByDate]
  );

  const goToPrevMonth = () => {
    if (month === 0) { setYear((y) => y - 1); setMonth(11); }
    else setMonth((m) => m - 1);
  };

  const goToNextMonth = () => {
    if (month === 11) { setYear((y) => y + 1); setMonth(0); }
    else setMonth((m) => m + 1);
  };

  const goToToday = () => {
    const today = new Date();
    setYear(today.getFullYear());
    setMonth(today.getMonth());
  };

  const toggleStatus = (status: string) => {
    setStatusFilters((prev) =>
      prev.includes(status) ? prev.filter((s) => s !== status) : [...prev, status]
    );
  };

  return (
    <div className="vr-space-y-5">
      <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-p-6">
        {/* Header */}
        <div className="vr-flex vr-items-start vr-justify-between vr-mb-4">
          <div>
            <h2 className="vr-text-base vr-font-bold vr-text-gray-900">Calendar</h2>
            <p className="vr-text-xs vr-text-gray-500 vr-mt-0.5">
              View your scheduled and published social posts.
            </p>
          </div>
          <a
            href={viralySsoUrl("/scheduler/calendar/all")}
            target="_blank"
            className="vr-inline-flex vr-items-center vr-gap-1.5 vr-px-3 vr-py-1.5 vr-bg-primary-600 vr-text-white vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-primary-700 vr-transition-colors"
          >
            <i className="fa-solid fa-calendar-days" style={{ fontSize: "10px" }} />
            Full Calendar
          </a>
        </div>

        {/* Success confirmation banner */}
        {successMsg && (
          <div className="vr-flex vr-items-center vr-justify-between vr-px-4 vr-py-3 vr-mb-4 vr-rounded-lg vr-bg-emerald-50 vr-border vr-border-emerald-200">
            <div className="vr-flex vr-items-center vr-gap-2">
              <i className="fa-solid fa-circle-check vr-text-emerald-500" style={{ fontSize: "14px" }} />
              <span className="vr-text-sm vr-font-medium vr-text-emerald-700">{successMsg}</span>
            </div>
            <button
              onClick={() => setSuccessMsg(null)}
              className="vr-text-emerald-400 hover:vr-text-emerald-600 vr-border-0 vr-bg-transparent vr-cursor-pointer vr-p-0"
            >
              <i className="fa-solid fa-xmark" style={{ fontSize: "12px" }} />
            </button>
          </div>
        )}

        {/* Month navigation */}
        <div className="vr-flex vr-items-center vr-justify-between vr-mb-4">
          <div className="vr-flex vr-items-center vr-gap-2">
            <button
              onClick={goToPrevMonth}
              className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-lg vr-bg-gray-100 vr-text-gray-600 hover:vr-bg-gray-200 vr-transition-colors vr-border-0 vr-cursor-pointer"
            >
              <i className="fa-solid fa-chevron-left" style={{ fontSize: "11px" }} />
            </button>
            <span className="vr-text-sm vr-font-semibold vr-text-gray-900 vr-min-w-[140px] vr-text-center">
              {MONTH_NAMES[month]} {year}
            </span>
            <button
              onClick={goToNextMonth}
              className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-lg vr-bg-gray-100 vr-text-gray-600 hover:vr-bg-gray-200 vr-transition-colors vr-border-0 vr-cursor-pointer"
            >
              <i className="fa-solid fa-chevron-right" style={{ fontSize: "11px" }} />
            </button>
            <button
              onClick={goToToday}
              className="vr-px-3 vr-py-1.5 vr-rounded-lg vr-bg-gray-100 vr-text-gray-600 vr-text-xs vr-font-medium hover:vr-bg-gray-200 vr-transition-colors vr-border-0 vr-cursor-pointer"
            >
              Today
            </button>
          </div>

          {/* Post count */}
          <span className="vr-text-xs vr-text-gray-400">
            {total} post{total !== 1 ? "s" : ""}
          </span>
        </div>

        {/* Filters */}
        <div className="vr-flex vr-items-center vr-justify-between vr-mb-4 vr-flex-wrap vr-gap-2">
          {/* Channel filter */}
          <select
            value={channelFilter || ""}
            onChange={(e) => setChannelFilter(e.target.value || null)}
            className="vr-text-xs vr-text-gray-700 vr-bg-white vr-border vr-border-gray-200 vr-rounded-lg vr-px-3 vr-py-1.5 vr-cursor-pointer vr-outline-none focus:vr-border-primary-300"
          >
            <option value="">All Profiles</option>
            {activeChannels.map((ch) => (
              <option key={ch.id} value={ch.id}>
                {PLATFORM_ICONS[ch.type] || "🌐"} {ch.name}
              </option>
            ))}
          </select>

          {/* Status filters */}
          <div className="vr-flex vr-gap-1">
            {STATUS_FILTER_OPTIONS.map((opt) => (
              <button
                key={opt.key}
                onClick={() => toggleStatus(opt.key)}
                className={clsx(
                  "vr-inline-flex vr-items-center vr-gap-1 vr-px-2.5 vr-py-1 vr-rounded-full vr-text-xs vr-font-medium vr-border-0 vr-cursor-pointer vr-transition-all",
                  statusFilters.includes(opt.key)
                    ? "vr-bg-gray-800 vr-text-white"
                    : "vr-bg-gray-100 vr-text-gray-500 hover:vr-bg-gray-200"
                )}
              >
                <span className={`vr-w-1.5 vr-h-1.5 vr-rounded-full ${opt.dot}`} />
                {opt.label}
              </button>
            ))}
          </div>
        </div>

        {/* Calendar content */}
        {isLoading || channelsLoading ? (
          <div className="vr-flex vr-items-center vr-justify-center vr-gap-3 vr-py-16 vr-text-gray-400 vr-text-sm">
            <div className="vr-w-5 vr-h-5 vr-border-2 vr-border-gray-200 vr-border-t-primary-600 vr-rounded-full vr-animate-spin" />
            Loading calendar...
          </div>
        ) : hasError ? (
          <div className="vr-text-center vr-py-16">
            <i className="fa-solid fa-triangle-exclamation vr-text-2xl vr-text-amber-400 vr-mb-3" />
            <p className="vr-text-sm vr-text-gray-500">Failed to load posts. Please try again.</p>
          </div>
        ) : activeChannels.length === 0 ? (
          <div className="vr-text-center vr-py-16">
            <i className="fa-solid fa-calendar vr-text-3xl vr-text-gray-200 vr-mb-3" />
            <h3 className="vr-text-sm vr-font-semibold vr-text-gray-900 vr-mb-1">No Profiles Connected</h3>
            <p className="vr-text-xs vr-text-gray-500 vr-mb-3">Connect social profiles to see your scheduled posts.</p>
            <button
              onClick={() => onNavigate?.("profiles")}
              className="vr-text-xs vr-font-semibold vr-text-primary-600 vr-border-0 vr-bg-transparent vr-cursor-pointer hover:vr-underline vr-p-0"
            >
              Connect profiles →
            </button>
          </div>
        ) : (
          <CalendarGrid days={days} onPostClick={setSelectedPost} onCreatePost={onCreatePost} />
        )}
      </div>

      {/* Post detail panel */}
      {selectedPost && (
        <PostDetailPanel post={selectedPost} onClose={() => setSelectedPost(null)} onDeleted={handlePostDeleted} />
      )}
    </div>
  );
}
