"use client";

import { useState } from "react";
import Modal from "@/components/Modal";
import ViewReportModal from "./ViewReportModal";
import { useTranslations } from "next-intl";
import type { PMCompletedScreeningData } from "@/api/user/generated.schemas";

interface ScreensCompletedModalProps {
  isOpen: boolean;
  onClose: () => void;
  data?: PMCompletedScreeningData[];
  isLoading?: boolean;
}

function mapRiskLevel(riskLevel?: string): "High Risk" | "Moderate Risk" | "Mild" | "Low Risk" {
  if (!riskLevel) return "Low Risk";
  const lower = riskLevel.toLowerCase();
  if (lower.includes("high")) return "High Risk";
  if (lower.includes("moderate") || lower.includes("medium")) return "Moderate Risk";
  if (lower.includes("mild")) return "Mild";
  return "Low Risk";
}

export default function ScreensCompletedModal({
  isOpen,
  onClose,
  data,
  isLoading,
}: ScreensCompletedModalProps) {
  const t = useTranslations("practiceManager");
  const [autoDownloadUuid, setAutoDownloadUuid] = useState<string | null>(null);
  const [viewingScreeningUuid, setViewingScreeningUuid] = useState<string | null>(null);
  const [viewingRisk, setViewingRisk] = useState<string | null>(null);
  const [viewingClientName, setViewingClientName] = useState<string | null>(null);
  const [viewingClientAge, setViewingClientAge] = useState<number | null>(null);

  const completedScreens = data || [];

  const getRiskBadgeStyles = (risk: string) => {
    switch (risk) {
      case "High Risk":
        return "bg-red-50 text-red-600 border border-red-100";
      case "Moderate Risk":
        return "bg-red-50 text-red-600 border border-red-100";
      case "Mild":
        return "bg-yellow-50 text-yellow-600 border border-yellow-100";
      case "Low Risk":
        return "bg-green-50 text-green-600 border border-green-100";
      default:
        return "bg-gray-50 text-gray-600 border border-gray-100";
    }
  };

  const getRiskLabel = (risk: string) => {
    switch (risk) {
      case "High Risk":
        return t("modals.screensCompleted.highRisk");
      case "Moderate Risk":
        return t("modals.screensCompleted.moderateRisk");
      case "Mild":
        return t("modals.screensCompleted.mildRisk");
      case "Low Risk":
        return t("modals.screensCompleted.lowRisk");
      default:
        return risk || "-";
    }
  };

  const handleViewReport = (screeningUuid: string, riskCategory: string, clientName?: string, clientAge?: number) => {
    setViewingScreeningUuid(screeningUuid);
    setViewingRisk(riskCategory);
    setViewingClientName(clientName || null);
    setViewingClientAge(clientAge ?? null);
  };


  return (
    <>
      <Modal isOpen={isOpen} onClose={onClose} size="3xl">
        <div>
          {/* Title */}
          <h2 className="text-2xl font-bold text-green-500 mb-6">
            {t("modals.screensCompleted.title")}
          </h2>

          {/* Table */}
          <div className="border border-gray-300 rounded-xl overflow-hidden">
            <div className="overflow-x-auto">
            <table className="w-full min-w-[600px]">
              <thead>
                <tr className="bg-white border-b border-gray-300">
                  <th className="text-left px-5 py-4 text-sm font-medium text-gray-600">{t("modals.screensCompleted.clientsName")}</th>
                  <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("modals.screensCompleted.mobileNumber")}</th>
                  <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("modals.screensCompleted.gender")}</th>
                  <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("modals.screensCompleted.age")}</th>
                  <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("modals.screensCompleted.suicideRiskCategory")}</th>
                  <th className="text-left px-5 py-4 text-sm font-medium text-gray-600 border-l border-gray-300">{t("modals.screensCompleted.action")}</th>
                </tr>
              </thead>
              <tbody>
                {isLoading ? (
                  <tr>
                    <td colSpan={6} 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>
                ) : completedScreens.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="py-8 text-center text-gray-500">
                      {t("modals.screensCompleted.noData")}
                    </td>
                  </tr>
                ) : (
                  completedScreens.map((screen, index) => {
                    const riskCategory = mapRiskLevel(screen.suicide_risk_category);
                    return (
                      <tr key={screen.screening_uuid || index} className="border-b border-gray-200 last:border-b-0 hover:bg-gray-50/50 transition">
                        <td className="px-5 py-4">
                          <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-full bg-[#E8F4F8] flex items-center justify-center text-[#3B9EC9] font-semibold text-sm">
                              {(screen.client_name || "U").charAt(0).toUpperCase()}
                            </div>
                            <div>
                              <p className="text-sm font-medium text-gray-900">{screen.client_name || "Unknown"}</p>
                              <p className="text-xs text-gray-500">{screen.client_email || ""}</p>
                            </div>
                          </div>
                        </td>
                        <td className="px-5 py-4 text-sm text-gray-600 border-l border-gray-200">{screen.mobile_number || "-"}</td>
                        <td className="px-5 py-4 text-sm text-gray-600 border-l border-gray-200">{screen.gender || "-"}</td>
                        <td className="px-5 py-4 text-sm text-gray-600 border-l border-gray-200">{screen.age || "-"}</td>
                        <td className="px-5 py-4 border-l border-gray-200">
                          <span
                            className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium ${getRiskBadgeStyles(riskCategory)}`}
                          >
                            <span
                              className={`w-1.5 h-1.5 rounded-full ${
                                riskCategory === "High Risk"
                                  ? "bg-red-500"
                                  : riskCategory === "Moderate Risk"
                                  ? "bg-red-500"
                                  : riskCategory === "Mild"
                                  ? "bg-yellow-500"
                                  : "bg-green-500"
                              }`}
                            />
                            {getRiskLabel(riskCategory)}
                          </span>
                        </td>
                        <td className="px-5 py-4 border-l border-gray-200">
                          <div className="flex items-center gap-3">
                            {/* Download Button */}
                            <button
                              onClick={() => screen.screening_uuid && setAutoDownloadUuid(screen.screening_uuid)}
                              disabled={autoDownloadUuid === screen.screening_uuid}
                              className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                              title="Download"
                            >
                              {autoDownloadUuid === screen.screening_uuid ? (
                                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[#3B9EC9]"></div>
                              ) : (
                                <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                                </svg>
                              )}
                            </button>
                            {/* View Button */}
                            <button
                              onClick={() => screen.screening_uuid && handleViewReport(screen.screening_uuid, screen.suicide_risk_category, screen.client_name || undefined, screen.age ?? undefined)}
                              className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition cursor-pointer"
                              title="View"
                            >
                              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                                <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>
                          </div>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
            </div>
          </div>
        </div>
      </Modal>

      {autoDownloadUuid && (
        <ViewReportModal
          isOpen={false}
          autoDownload
          screeningUuid={autoDownloadUuid}
          onClose={() => setAutoDownloadUuid(null)}
        />
      )}

      {/* View Report Popup */}
      <ViewReportModal
        isOpen={!!viewingScreeningUuid}
        onClose={() => { setViewingScreeningUuid(null); setViewingRisk(null); setViewingClientName(null); setViewingClientAge(null); }}
        screeningUuid={viewingScreeningUuid}
        suicideRisk={viewingRisk || undefined}
        clientName={viewingClientName || undefined}
        clientAge={viewingClientAge}
      />

</>
  );
}
