"use client";

import { useState } from "react";
import Modal from "@/components/Modal";
import { useTranslations, useLocale } from "next-intl";
import { toast } from "react-hot-toast";
import { customInstance } from "@/config/axios";
import { usePMClientsControllerGetClientScreeningsV1 } from "@/api/user/practice-manager-clients/practice-manager-clients";
import ViewReportModal from "./ViewReportModal";

interface ScreeningReportsModalProps {
  isOpen: boolean;
  onClose: () => void;
  patientName: string;
  clientUuid?: string;
}

export default function ScreeningReportsModal({
  isOpen,
  onClose,
  patientName,
  clientUuid,
}: ScreeningReportsModalProps) {
  const locale = useLocale();
  const t = useTranslations("practiceManager");
  const [confirmSendUuid, setConfirmSendUuid] = useState<string | null>(null);
  const [isSending, setIsSending] = useState(false);
  const [viewingScreeningUuid, setViewingScreeningUuid] = useState<string | null>(null);

  // Fetch screenings from API when modal is open and clientUuid is provided
  const { data: screeningsResponse, isLoading } =
    usePMClientsControllerGetClientScreeningsV1(
      clientUuid || "",
      { page: 1, limit: 50 },
      {
        query: {
          enabled: isOpen && !!clientUuid,
        },
      }
    );

  // Filter to only show completed screenings (matching practitioner behavior)
  const allScreenings = (screeningsResponse as any)?.data || [];
  const screenings = allScreenings.filter(
    (s: any) => s.status?.toLowerCase() === "completed"
  );

  const getRiskBadgeStyles = (risk: string) => {
    if (!risk) return "bg-gray-50 text-gray-600 border border-gray-100";
    const lower = risk.toLowerCase();
    if (lower.includes("high")) return "bg-red-50 text-red-600 border border-red-100";
    if (lower.includes("moderate") || lower.includes("medium")) return "bg-red-50 text-red-600 border border-red-100";
    if (lower.includes("mild")) return "bg-yellow-50 text-yellow-600 border border-yellow-100";
    if (lower.includes("low")) return "bg-green-50 text-green-600 border border-green-100";
    return "bg-gray-50 text-gray-600 border border-gray-100";
  };

  const getRiskDotColor = (risk: string) => {
    if (!risk) return "bg-gray-500";
    const lower = risk.toLowerCase();
    if (lower.includes("high")) return "bg-red-500";
    if (lower.includes("moderate") || lower.includes("medium")) return "bg-red-500";
    if (lower.includes("mild")) return "bg-yellow-500";
    if (lower.includes("low")) return "bg-green-500";
    return "bg-gray-500";
  };

  const getRiskLabel = (risk: string) => {
    if (!risk) return "-";
    const lower = risk.toLowerCase();
    if (lower.includes("high") || lower.includes("moderate") || lower.includes("medium")) return t("modals.screeningReports.moderateRisk");
    if (lower.includes("mild")) return t("modals.screeningReports.mildRisk");
    if (lower.includes("low")) return t("modals.screeningReports.lowRisk");
    return risk;
  };

  const formatDate = (dateStr: string) => {
    try {
      const date = new Date(dateStr);
      return date.toLocaleDateString(locale === "es" ? "es-ES" : "en-US", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      });
    } catch {
      return dateStr;
    }
  };

  const handleConfirmSend = async () => {
    if (!confirmSendUuid) return;
    setIsSending(true);
    try {
      await customInstance({
        url: `/v1/practice-manager/screenings/${confirmSendUuid}/share`,
        method: "POST",
      });
      toast.success(t("modals.screeningReports.reportSent"));
      setConfirmSendUuid(null);
    } catch (error: any) {
      const message = error?.response?.data?.message;
      toast.error(message || t("modals.screeningReports.reportSendFailed"));
    } finally {
      setIsSending(false);
    }
  };

  return (
    <>
    <Modal isOpen={isOpen} onClose={onClose} size="3xl">
      <div className="p-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-xl font-semibold text-gray-900">
            {t("modals.screeningReports.title")} ({patientName})
          </h2>
        </div>

        {/* Table */}
        <div className="overflow-x-auto border border-gray-200 rounded-lg">
          <table className="w-full border-collapse">
            <thead>
              <tr className="border-b border-gray-200 bg-gray-50">
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 w-20 border-r border-gray-200">
                  {t("modals.screeningReports.no")}
                </th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">
                  {t("modals.screeningReports.screeningDate")}
                </th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">
                  {t("modals.screeningReports.risk")}
                </th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-500 w-32">
                  {t("modals.screeningReports.action")}
                </th>
              </tr>
            </thead>
            <tbody>
              {isLoading ? (
                <tr>
                  <td colSpan={4} className="py-8 text-center text-gray-500">
                    <div className="flex justify-center">
                      <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
                    </div>
                  </td>
                </tr>
              ) : screenings.length === 0 ? (
                <tr>
                  <td colSpan={4} className="py-8 text-center text-gray-500">
                    {t("modals.screeningReports.noScreenings")}
                  </td>
                </tr>
              ) : (
                screenings.map((screening: any, index: number) => (
                  <tr
                    key={screening.uuid}
                    className="border-b border-gray-200 last:border-0 hover:bg-gray-50/50 transition"
                  >
                    <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">
                      {index + 1}
                    </td>
                    <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">
                      {formatDate(screening.created_at)}
                    </td>
                    <td className="py-4 px-4 border-r border-gray-200">
                      {screening.suicide_risk_category ? (
                        <span
                          className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium ${getRiskBadgeStyles(screening.suicide_risk_category)}`}
                        >
                          <span className={`w-1.5 h-1.5 rounded-full ${getRiskDotColor(screening.suicide_risk_category)}`} />
                          {getRiskLabel(screening.suicide_risk_category)}
                        </span>
                      ) : (
                        <span className="text-sm text-gray-400">-</span>
                      )}
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex items-center justify-center gap-2">
                        {/* View Report */}
                        <button
                          onClick={() => setViewingScreeningUuid(screening.uuid)}
                          className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition"
                          title={t("modals.screeningReports.viewReport")}
                        >
                          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                          </svg>
                        </button>
                        {/* Send to Client */}
                        <button
                          onClick={() => setConfirmSendUuid(screening.uuid)}
                          className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition"
                          title={t("modals.screeningReports.sendToClient")}
                        >
                          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
                          </svg>
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

    </Modal>

      {/* Send to Client Confirmation */}
      {/* View Report Modal */}
      <ViewReportModal
        isOpen={!!viewingScreeningUuid}
        onClose={() => setViewingScreeningUuid(null)}
        screeningUuid={viewingScreeningUuid}
        clientName={patientName}
      />

      {confirmSendUuid !== null && (
        <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50" onClick={() => setConfirmSendUuid(null)}>
          <div className="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-sm mx-4" onClick={(e) => e.stopPropagation()}>
            {/* Icon */}
            <div className="flex justify-center mb-4">
              <div className="w-14 h-14 rounded-full bg-[#3B9EC9]/10 flex items-center justify-center">
                <svg className="w-7 h-7 text-[#3B9EC9]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
                </svg>
              </div>
            </div>
            {/* Title */}
            <h3 className="text-lg font-semibold text-gray-900 text-center mb-2">
              {t("modals.screeningReports.sendConfirmTitle")}
            </h3>
            {/* Message */}
            <p className="text-sm text-gray-500 text-center mb-6 leading-relaxed">
              {t("modals.screeningReports.sendConfirmMessage") || `Are you sure you want to send this report to ${patientName}? They will be able to view it after logging in.`}
            </p>
            {/* Buttons */}
            <div className="flex gap-3">
              <button
                onClick={() => setConfirmSendUuid(null)}
                disabled={isSending}
                className="flex-1 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 rounded-xl hover:bg-gray-200 transition disabled:opacity-50 cursor-pointer"
              >
                {t("modals.screeningReports.confirmNo")}
              </button>
              <button
                onClick={handleConfirmSend}
                disabled={isSending}
                className="flex-1 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-xl hover:bg-[#2D8AB5] transition disabled:opacity-50 flex items-center justify-center gap-2 cursor-pointer"
              >
                {isSending && <span className="w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin" />}
                {t("modals.screeningReports.confirmYes")}
              </button>
            </div>
          </div>
        </div>
      )}

    </>
  );
}
