"use client";

import Modal from "@/components/Modal";
import ViewReportModal from "./ViewReportModal";
import { useState } from "react";
import { useTranslations } from "next-intl";
import { usePractitionerDashboardControllerGetHighRiskCasesV1 } from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import { HighRiskCaseData } from "@/api/user/generated.schemas";

interface HighRiskCasesModalProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function HighRiskCasesModal({ isOpen, onClose }: HighRiskCasesModalProps) {
  const t = useTranslations("practitioner");
  const [autoDownloadClientId, setAutoDownloadClientId] = useState<number | null>(null);
  const [autoDownloadScreeningId, setAutoDownloadScreeningId] = useState<number | null>(null);
  const [viewingClientId, setViewingClientId] = useState<number | null>(null);
  const [viewingScreeningId, setViewingScreeningId] = useState<number | null>(null);
  const [viewingRisk, setViewingRisk] = useState<string | null>(null);
  const [viewingClientName, setViewingClientName] = useState<string | null>(null);
  const [viewingClientAge, setViewingClientAge] = useState<number | null>(null);

  // Fetch high-risk cases from API
  const { data: response, isLoading } = usePractitionerDashboardControllerGetHighRiskCasesV1(
    { page: 1, limit: 100 },
    { query: { enabled: isOpen } }
  );

  const highRiskCases: HighRiskCaseData[] = (response as any)?.data || [];

  const handleViewReport = (clientId: number, screeningId: number, risk: string, name: string, age: number | null) => {
    setViewingClientId(clientId);
    setViewingScreeningId(screeningId);
    setViewingRisk(risk);
    setViewingClientName(name);
    setViewingClientAge(age);
  };

  // Format date helper
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", { day: "2-digit", month: "short", year: "numeric" });
  };

  const DownloadIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
    </svg>
  );

  const ViewIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" />
      <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
    </svg>
  );

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

        {/* 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 border-r border-gray-200 min-w-[180px]">{t("modals.highRiskCases.clientName")}</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.highRiskCases.mobileNumber")}</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.highRiskCases.gender")}</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.highRiskCases.age")}</th>
                <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.highRiskCases.screeningDate")}</th>
                <th className="text-center py-3 px-4 text-sm font-medium text-gray-500">{t("modals.highRiskCases.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>
              ) : highRiskCases.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-8 text-center text-gray-500">
                    {t("modals.highRiskCases.noData")}
                  </td>
                </tr>
              ) : (
                highRiskCases.map((caseItem, index) => (
                  <tr key={caseItem.screening_id} className={`${index !== highRiskCases.length - 1 ? 'border-b border-gray-200' : ''} hover:bg-gray-50/50 transition`}>
                    {/* Client Name with Avatar */}
                    <td className="py-4 px-4 border-r border-gray-200">
                      <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden flex-shrink-0">
                          <svg className="w-6 h-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                          </svg>
                        </div>
                        <div>
                          <p className="text-sm font-medium text-gray-900">{caseItem.client_name}</p>
                          <p className="text-sm text-gray-500">{caseItem.client_email || "-"}</p>
                        </div>
                      </div>
                    </td>
                    {/* Mobile Number */}
                    <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-200">{caseItem.mobile_number || "-"}</td>
                    {/* Gender */}
                    <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-200">{caseItem.gender || "-"}</td>
                    {/* Age */}
                    <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-200">{caseItem.age || "-"}</td>
                    {/* Screening Date */}
                    <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-200">{formatDate(caseItem.screening_date)}</td>
                    {/* Actions */}
                    <td className="py-4 px-4">
                      <div className="flex items-center justify-center gap-3">
                        <button
                          onClick={() => { setAutoDownloadClientId(caseItem.client_id); setAutoDownloadScreeningId(caseItem.screening_id); }}
                          disabled={autoDownloadScreeningId === caseItem.screening_id}
                          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"
                        >
                          {autoDownloadScreeningId === caseItem.screening_id ? (
                            <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[#3B9EC9]"></div>
                          ) : (
                            <DownloadIcon />
                          )}
                        </button>
                        <button
                          onClick={() => handleViewReport(caseItem.client_id, caseItem.screening_id, caseItem.suicide_risk_category, caseItem.client_name, caseItem.age ?? null)}
                          className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition cursor-pointer"
                        >
                          <ViewIcon />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </Modal>

      {autoDownloadScreeningId && (
        <ViewReportModal
          isOpen={false}
          autoDownload
          clientId={autoDownloadClientId ?? undefined}
          screeningId={autoDownloadScreeningId}
          onClose={() => { setAutoDownloadClientId(null); setAutoDownloadScreeningId(null); }}
        />
      )}

      {/* View Report Modal */}
      <ViewReportModal
        isOpen={!!viewingScreeningId}
        onClose={() => { setViewingClientId(null); setViewingScreeningId(null); setViewingRisk(null); setViewingClientName(null); setViewingClientAge(null); }}
        clientId={viewingClientId ?? undefined}
        screeningId={viewingScreeningId}
        suicideRisk={viewingRisk || undefined}
        clientName={viewingClientName || undefined}
        clientAge={viewingClientAge}
      />
    </>
  );
}
