import { useState } from "react";
import { PLATFORM_ICONS, STATUS_STYLES } from "../shared";
import { PLATFORM_META } from "../ChannelSelector";
import { wpApi } from "../../api/wp-api";
import { toast } from "react-toastify";
import type { EnrichedCalendarPost } from "../../hooks/useCalendarPosts";
import { viralySsoUrl } from "../../utils/sso";

interface Props {
  post: EnrichedCalendarPost;
  onClose: () => void;
  onDeleted?: () => void;
}

export default function PostDetailPanel({ post, onClose, onDeleted }: Props) {
  const [deleting, setDeleting] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);

  const isEditable = post.displayStatus === "Scheduled" || post.displayStatus === "Draft";

  // Build deep-link URL to open the post editor in Viraly SPA
  // Format: ?composer=base64("p:postId;a:edit")
  const editUrl = (() => {
    const paramStr = `p:${post.id};a:${post.displayStatus === "Published" ? "view" : "edit"}`;
    const base64 = btoa(paramStr).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
    return viralySsoUrl(`/scheduler/calendar/all?composer=${base64}`);
  })();

  const handleDelete = async () => {
    setDeleting(true);
    try {
      const baseUrl = (window as any).viralyWP.restUrl.replace(/\/+$/, "");
      const nonce = (window as any).viralyWP.restNonce;
      const res = await fetch(`${baseUrl}/social-posts/${post.id}`, {
        method: "DELETE",
        credentials: "same-origin",
        headers: { "X-WP-Nonce": nonce, "Content-Type": "application/json" },
      });
      if (res.ok) {
        toast.success("Post deleted");
        onDeleted?.();
        onClose();
      } else {
        const data = await res.json().catch(() => null);
        toast.error(data?.error || "Failed to delete post");
      }
    } catch {
      toast.error("Failed to delete post");
    } finally {
      setDeleting(false);
      setConfirmDelete(false);
    }
  };

  const status = STATUS_STYLES[post.displayStatus] || STATUS_STYLES.Draft;
  const platformMeta = PLATFORM_META[post.channelType] || { icon: "fa-solid fa-globe", color: "#666" };
  const icon = PLATFORM_ICONS[post.channelType] || "🌐";

  const scheduledDate = post.scheduledAt
    ? new Date(post.scheduledAt).toLocaleDateString(undefined, { weekday: "long", month: "long", day: "numeric", year: "numeric" })
    : "Unscheduled";
  const scheduledTime = post.scheduledAt
    ? new Date(post.scheduledAt).toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" })
    : "";

  return (
    <div className="vr-fixed vr-inset-0 vr-z-50 vr-flex vr-justify-end" onClick={onClose}>
      {/* Backdrop */}
      <div className="vr-absolute vr-inset-0 vr-bg-black/20" />

      {/* Panel */}
      <div
        className="vr-relative vr-w-full vr-max-w-sm vr-bg-white vr-shadow-2xl vr-overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="vr-sticky vr-top-0 vr-bg-white vr-border-b vr-border-gray-200 vr-px-5 vr-py-4 vr-flex vr-items-center vr-justify-between vr-z-10">
          <div className="vr-flex vr-items-center vr-gap-2.5">
            <span className="vr-text-lg">{icon}</span>
            <div>
              <p className="vr-text-sm vr-font-semibold vr-text-gray-900">{post.channelName}</p>
              <p className="vr-text-xs vr-text-gray-400">{post.channelType}</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="vr-w-8 vr-h-8 vr-flex vr-items-center vr-justify-center vr-rounded-full hover:vr-bg-gray-100 vr-text-gray-400 hover:vr-text-gray-600 vr-border-0 vr-bg-transparent vr-cursor-pointer"
          >
            <i className="fa-solid fa-xmark" />
          </button>
        </div>

        {/* Content */}
        <div className="vr-p-5 vr-space-y-5">
          {/* Status + Date */}
          <div className="vr-flex vr-items-center vr-justify-between">
            <span className={`vr-inline-flex vr-items-center vr-gap-1.5 vr-px-2.5 vr-py-1 vr-rounded-full vr-text-xs vr-font-semibold ${status.bg} ${status.text}`}>
              {status.label}
            </span>
            <div className="vr-text-right">
              <p className="vr-text-xs vr-font-medium vr-text-gray-700">{scheduledDate}</p>
              {scheduledTime && <p className="vr-text-xs vr-text-gray-400">{scheduledTime}</p>}
            </div>
          </div>

          {/* Thumbnail */}
          {post.thumbnailUrl && (
            <img
              src={post.thumbnailUrl}
              alt=""
              className="vr-w-full vr-rounded-lg vr-object-cover"
              style={{ maxHeight: "200px" }}
            />
          )}

          {/* Caption */}
          <div>
            <h4 className="vr-text-xs vr-font-semibold vr-text-gray-400 vr-uppercase vr-tracking-wide vr-mb-1.5">Caption</h4>
            <p className="vr-text-sm vr-text-gray-700 vr-leading-relaxed vr-whitespace-pre-line">
              {post.title || "No caption"}
            </p>
          </div>

          {/* Attachment info */}
          {post.attachmentCount > 0 && (
            <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-gray-500">
              <i className={`fa-solid ${post.attachmentType === "Video" ? "fa-video" : post.attachmentType === "Document" ? "fa-file" : "fa-image"}`} style={{ fontSize: "11px" }} />
              <span>
                {post.attachmentCount} {post.attachmentType || "attachment"}{post.attachmentCount !== 1 ? "s" : ""}
              </span>
            </div>
          )}

          {/* Evergreen badge */}
          {post.isEvergreen && (
            <div className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-text-emerald-600 vr-bg-emerald-50 vr-px-3 vr-py-2 vr-rounded-lg">
              <i className="fa-solid fa-recycle" style={{ fontSize: "11px" }} />
              <span>{post.isEvergreenRoot ? "Evergreen Source" : "Recycled Post"}</span>
            </div>
          )}

          {/* Error */}
          {post.error && (
            <div className="vr-text-xs vr-text-red-600 vr-bg-red-50 vr-px-3 vr-py-2 vr-rounded-lg">
              <i className="fa-solid fa-circle-exclamation vr-mr-1.5" style={{ fontSize: "10px" }} />
              {post.error.message || "Post failed"}
            </div>
          )}

          {/* External link */}
          {post.externalUrl && (
            <a
              href={post.externalUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="vr-flex vr-items-center vr-gap-2 vr-text-xs vr-font-medium vr-text-primary-600 hover:vr-underline"
            >
              <i className="fa-solid fa-arrow-up-right-from-square" style={{ fontSize: "10px" }} />
              View on {post.channelType}
            </a>
          )}
        </div>

        {/* Actions for scheduled/draft posts */}
        {isEditable && (
          <div className="vr-px-5 vr-py-3 vr-border-t vr-border-gray-100 vr-flex vr-items-center vr-gap-2">
            <a
              href={editUrl}
              target="_blank"
              className="vr-flex-1 vr-inline-flex vr-items-center vr-justify-center vr-gap-1.5 vr-px-3 vr-py-2 vr-bg-gray-100 vr-text-gray-700 vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-gray-200 vr-transition-colors vr-no-underline"
            >
              <i className="fa-solid fa-pen" style={{ fontSize: "10px" }} />
              Edit in Viraly
            </a>
            {!confirmDelete ? (
              <button
                onClick={() => setConfirmDelete(true)}
                className="vr-inline-flex vr-items-center vr-justify-center vr-gap-1.5 vr-px-3 vr-py-2 vr-bg-red-50 vr-text-red-600 vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-red-100 vr-transition-colors vr-border-0 vr-cursor-pointer"
              >
                <i className="fa-solid fa-trash-can" style={{ fontSize: "10px" }} />
                Delete
              </button>
            ) : (
              <div className="vr-flex vr-items-center vr-gap-1">
                <button
                  onClick={handleDelete}
                  disabled={deleting}
                  className="vr-px-3 vr-py-2 vr-bg-red-600 vr-text-white vr-rounded-lg vr-text-xs vr-font-semibold hover:vr-bg-red-700 vr-transition-colors vr-border-0 vr-cursor-pointer disabled:vr-opacity-50"
                >
                  {deleting ? "Deleting..." : "Confirm"}
                </button>
                <button
                  onClick={() => setConfirmDelete(false)}
                  className="vr-px-2 vr-py-2 vr-text-xs vr-text-gray-500 vr-border-0 vr-bg-transparent vr-cursor-pointer"
                >
                  Cancel
                </button>
              </div>
            )}
          </div>
        )}

        {/* Footer */}
        <div className="vr-border-t vr-border-gray-100 vr-px-5 vr-py-3">
          <a
            href={viralySsoUrl("/scheduler/calendar/all")}
            target="_blank"
            className="vr-flex vr-items-center vr-justify-center vr-gap-1.5 vr-text-xs vr-font-medium vr-text-gray-500 hover:vr-text-primary-600 vr-transition-colors"
          >
            Open full calendar in Viraly
            <i className="fa-solid fa-arrow-up-right-from-square" style={{ fontSize: "9px" }} />
          </a>
        </div>
      </div>
    </div>
  );
}
