"use client";

import { useEffect, useState } from "react";
import { useToast } from "@/lib/toast";
import { getStoredUser } from "@/lib/utils/persistAuth";

interface ReportReason {
  id: number;
  type: number;
  reason: string;
  status: number;
}

interface ReportResponse {
  status: number;
  result: ReportReason[];
}

interface ReportModalProps {
  open: boolean;
  onClose: () => void;
  /** 1=Article, 2=Clips, 4=Show */
  type: number;
  contentId: number;
  videoId?: number;
}

export default function ReportModal({
  open,
  onClose,
  type,
  contentId,
  videoId = 0,
}: ReportModalProps) {
  const { success, error: showError } = useToast();
  const [userId, setUserId] = useState(0);
  useEffect(() => {
    setUserId(getStoredUser()?.id ?? 0);
  }, []);
  const [reasons, setReasons] = useState<ReportReason[]>([]);
  const [selected, setSelected] = useState<string>("");
  const [custom, setCustom] = useState("");
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (!open) return;
    setSelected("");
    setCustom("");

    (async () => {
      try {
        const { default: apiClient } = await import("@/services/api.client");
        const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
        const { data } = await apiClient.post<ReportResponse>(
          API_ENDPOINTS.GET_REPORT_REASON,
          { type },
        );
        setReasons(data.result ?? []);
      } catch {
        setReasons([]);
      }
    })();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, type]);

  async function handleSubmit() {
    const reason = selected === "__custom__" ? custom.trim() : selected;
    if (!reason || !userId) return;
    setSubmitting(true);
    try {
      const { default: apiClient } = await import("@/services/api.client");
      const { API_ENDPOINTS } = await import("@/lib/constants/apiEndpoints");
      await apiClient.post(API_ENDPOINTS.ADD_CONTENT_REPORT, {
        user_id: userId,
        type,
        content_id: contentId,
        reason,
        video_id: videoId,
      });
      success("Report submitted — thank you");
      onClose();
    } catch {
      showError("Failed to submit report");
    } finally {
      setSubmitting(false);
    }
  }

  if (!open) return null;

  const canSubmit = !!(selected === "__custom__" ? custom.trim() : selected);

  return (
    <>
      {/* Backdrop */}
      <div
        onClick={onClose}
        style={{
          position: "fixed",
          inset: 0,
          background: "rgba(0,0,0,0.5)",
          backdropFilter: "blur(3px)",
          zIndex: 900,
        }}
      />

      {/* Modal */}
      <div
        style={{
          position: "fixed",
          top: "50%",
          left: "50%",
          transform: "translate(-50%,-50%)",
          zIndex: 901,
          background: "var(--surf, #ffffff)",
          borderRadius: 14,
          width: "min(440px, 92vw)",
          boxShadow: "0 24px 64px rgba(0,0,0,0.25)",
          overflow: "hidden",
        }}
      >
        {/* Header */}
        <div
          style={{
            padding: "1.25rem 1.375rem 0",
            borderBottom: "1px solid var(--border)",
            paddingBottom: "1rem",
          }}
        >
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
            }}
          >
            <div
              style={{ display: "flex", alignItems: "center", gap: "0.625rem" }}
            >
              <span
                style={{
                  width: 32,
                  height: 32,
                  borderRadius: "50%",
                  background: "#fef2f2",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: 16,
                }}
              >
                🚩
              </span>
              <div>
                <h3
                  style={{
                    margin: 0,
                    fontSize: "0.9375rem",
                    fontWeight: 700,
                    color: "var(--ink)",
                  }}
                >
                  Report content
                </h3>
                <p
                  style={{
                    margin: 0,
                    fontSize: "0.75rem",
                    color: "var(--text-2, #6b7280)",
                  }}
                >
                  Help us understand what's wrong
                </p>
              </div>
            </div>
            <button
              onClick={onClose}
              style={{
                background: "none",
                border: "none",
                cursor: "pointer",
                color: "var(--text-2, #6b7280)",
                fontSize: 18,
                width: 28,
                height: 28,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              ✕
            </button>
          </div>
        </div>

        {/* Reasons */}
        <div
          style={{
            padding: "1rem 1.375rem",
            maxHeight: "55vh",
            overflowY: "auto",
          }}
        >
          {reasons.length === 0 ? (
            <p
              style={{
                fontSize: "0.875rem",
                color: "var(--text-2, #6b7280)",
                textAlign: "center",
                padding: "1rem 0",
              }}
            >
              Loading reasons…
            </p>
          ) : (
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                gap: "0.5rem",
              }}
            >
              {reasons.map((r) => (
                <label
                  key={r.id}
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: "0.75rem",
                    padding: "0.75rem 0.875rem",
                    border: `1.5px solid ${selected === r.reason ? "var(--brand)" : "var(--border)"}`,
                    borderRadius: 8,
                    cursor: "pointer",
                    background:
                      selected === r.reason
                        ? "var(--brand-08, rgba(193,39,45,0.08))"
                        : "var(--surf, #ffffff)",
                    transition: "all 0.12s",
                  }}
                >
                  <div
                    style={{
                      flexShrink: 0,
                      width: 18,
                      height: 18,
                      borderRadius: "50%",
                      border: `2px solid ${selected === r.reason ? "var(--brand)" : "var(--border)"}`,
                      background:
                        selected === r.reason ? "var(--brand)" : "transparent",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      transition: "all 0.12s",
                    }}
                  >
                    {selected === r.reason && (
                      <div
                        style={{
                          width: 6,
                          height: 6,
                          borderRadius: "50%",
                          background: "#fff",
                        }}
                      />
                    )}
                  </div>
                  <input
                    type="radio"
                    name="report_reason"
                    value={r.reason}
                    checked={selected === r.reason}
                    onChange={() => setSelected(r.reason)}
                    style={{ display: "none" }}
                  />
                  <span
                    style={{
                      fontSize: "0.875rem",
                      fontWeight: selected === r.reason ? 600 : 400,
                      color: "var(--ink)",
                    }}
                  >
                    {r.reason}
                  </span>
                </label>
              ))}

              {/* Other option */}
              <label
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: "0.75rem",
                  padding: "0.75rem 0.875rem",
                  border: `1.5px solid ${selected === "__custom__" ? "var(--brand)" : "var(--border)"}`,
                  borderRadius: 8,
                  cursor: "pointer",
                  background:
                    selected === "__custom__"
                      ? "var(--brand-08, rgba(193,39,45,0.08))"
                      : "var(--surf, #ffffff)",
                  transition: "all 0.12s",
                }}
              >
                <div
                  style={{
                    flexShrink: 0,
                    width: 18,
                    height: 18,
                    borderRadius: "50%",
                    border: `2px solid ${selected === "__custom__" ? "var(--brand)" : "var(--border)"}`,
                    background:
                      selected === "__custom__"
                        ? "var(--brand)"
                        : "transparent",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    transition: "all 0.12s",
                  }}
                >
                  {selected === "__custom__" && (
                    <div
                      style={{
                        width: 6,
                        height: 6,
                        borderRadius: "50%",
                        background: "#fff",
                      }}
                    />
                  )}
                </div>
                <input
                  type="radio"
                  name="report_reason"
                  value="__custom__"
                  checked={selected === "__custom__"}
                  onChange={() => setSelected("__custom__")}
                  style={{ display: "none" }}
                />
                <span
                  style={{
                    fontSize: "0.875rem",
                    fontWeight: selected === "__custom__" ? 600 : 400,
                    color: "var(--ink)",
                  }}
                >
                  Other reason
                </span>
              </label>

              {selected === "__custom__" && (
                <textarea
                  value={custom}
                  onChange={(e) => setCustom(e.target.value)}
                  placeholder="Describe the issue…"
                  rows={3}
                  autoFocus
                  style={{
                    width: "100%",
                    padding: "0.625rem 0.75rem",
                    border: "1.5px solid var(--brand)",
                    borderRadius: 8,
                    fontSize: "0.875rem",
                    outline: "none",
                    resize: "none",
                    color: "var(--ink)",
                    background: "var(--surf, #ffffff)",
                    boxSizing: "border-box",
                  }}
                />
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div
          style={{
            padding: "0.875rem 1.375rem",
            borderTop: "1px solid var(--border)",
            display: "flex",
            gap: "0.625rem",
            justifyContent: "flex-end",
          }}
        >
          <button
            onClick={onClose}
            style={{
              padding: "0.5rem 1.25rem",
              background: "none",
              border: "1px solid var(--border)",
              borderRadius: 8,
              fontWeight: 600,
              fontSize: "0.875rem",
              cursor: "pointer",
              color: "var(--ink)",
            }}
          >
            Cancel
          </button>
          <button
            onClick={handleSubmit}
            disabled={!canSubmit || submitting || !userId}
            style={{
              padding: "0.5rem 1.25rem",
              background: canSubmit && userId ? "var(--brand)" : "#e5e7eb",
              color: canSubmit && userId ? "#fff" : "var(--text-3, #9ca3af)",
              border: "none",
              borderRadius: 8,
              fontWeight: 700,
              fontSize: "0.875rem",
              cursor: canSubmit && userId ? "pointer" : "default",
            }}
          >
            {submitting ? "Submitting…" : "Submit report"}
          </button>
        </div>
      </div>
    </>
  );
}
