"use client";

import { useState, useEffect } from "react";
import Modal from "@/components/Modal";
import { useTranslations } from "next-intl";
import { toast } from "react-hot-toast";
import { customInstance } from "@/config/axios";
import { usePractitionerDashboardControllerGetCompletedScreeningsV1 } from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import { CompletedScreeningData } from "@/api/user/generated.schemas";
import ViewReportModal from "@/components/practitioner/modals/ViewReportModal";

interface ScreeningReportsModalProps {
  isOpen: boolean;
  onClose: () => void;
  clientId?: number;
  clientName?: string;
  clientAge?: number | null;
  initialScreeningId?: number;
}

export default function ScreeningReportsModal({
  isOpen,
  onClose,
  clientId,
  clientName = "Client",
  initialScreeningId,
}: ScreeningReportsModalProps) {
  const t = useTranslations("practitioner");
  const [viewReport, setViewReport] = useState<{ clientId: number; screeningId: number; suicideRisk: string } | null>(null);

  const [confirmSendUuid, setConfirmSendUuid] = useState<string | null>(null);
  const [isSending, setIsSending] = useState(false);

  const handleConfirmSend = async () => {
    if (!confirmSendUuid) return;
    setIsSending(true);
    try {
      await customInstance({ url: `/v1/practitioner/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);
    }
  };

  const { data: response, isLoading } = usePractitionerDashboardControllerGetCompletedScreeningsV1(
    { page: 1, limit: 100 },
    { query: { enabled: isOpen && !!clientId } }
  );

  const screenings: CompletedScreeningData[] = ((response as any)?.data || []).filter(
    (s: CompletedScreeningData) => s.client_id === clientId
  );

  // Auto-open specific report when coming from email link
  useEffect(() => {
    if (!initialScreeningId || !clientId || isLoading || screenings.length === 0) return;
    const target = screenings.find(s => s.screening_id === initialScreeningId);
    if (target) {
      setViewReport({
        clientId: target.client_id!,
        screeningId: target.screening_id!,
        suicideRisk: target.suicide_risk_category || "",
      });
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initialScreeningId, clientId, isLoading, screenings.length]);

  const getRiskBadgeStyles = (risk: string) => {
    const normalizedRisk = risk?.toLowerCase();
    if (normalizedRisk?.includes("high")) return "bg-red-50 text-red-600 border border-red-100";
    if (normalizedRisk?.includes("moderate")) return "bg-red-50 text-red-600 border border-red-100";
    if (normalizedRisk?.includes("mild")) return "bg-yellow-50 text-yellow-600 border border-yellow-100";
    if (normalizedRisk?.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 getRiskLabel = (risk: string) => {
    const normalizedRisk = risk?.toLowerCase();
    if (normalizedRisk?.includes("high")) return t("modals.screeningReports.highRisk");
    if (normalizedRisk?.includes("moderate")) return t("modals.screeningReports.moderateRisk");
    if (normalizedRisk?.includes("mild")) return t("modals.screeningReports.mildRisk");
    if (normalizedRisk?.includes("low")) return t("modals.screeningReports.lowRisk");
    return risk || "-";
  };

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

  const EyeIcon = () => (
    <svg className="w-4 h-4" 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="p-6">
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-xl font-semibold text-gray-900">
              {t("modals.screeningReports.title")} ({clientName})
            </h2>
          </div>

          <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.suicideRiskCategory")}</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.noData")}
                    </td>
                  </tr>
                ) : (
                  screenings.map((screening, index) => (
                    <tr
                      key={screening.screening_id}
                      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.completed_at)}</td>
                      <td className="py-4 px-4 border-r border-gray-200">
                        {(() => {
                          const risk = screening.suicide_risk_category || "";
                          return risk ? (
                            <span className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium ${getRiskBadgeStyles(risk)}`}>
                              <span className="w-1.5 h-1.5 rounded-full bg-current"></span>
                              {getRiskLabel(risk)}
                            </span>
                          ) : (
                            <span className="text-gray-400">-</span>
                          );
                        })()}
                      </td>
                      <td className="py-4 px-4">
                        <div className="flex items-center justify-center gap-2">
                          {/* View Report */}
                          <button
                            onClick={() => setViewReport({
                              clientId: screening.client_id!,
                              screeningId: screening.screening_id!,
                              suicideRisk: screening.suicide_risk_category || "",
                            })}
                            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")}
                          >
                            <EyeIcon />
                          </button>
                          {/* Send to Client */}
                          <button
                            onClick={() => setConfirmSendUuid(screening.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>

      {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()}>
            <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>
            <h3 className="text-lg font-semibold text-gray-900 text-center mb-2">
              {t("modals.screeningReports.sendConfirmTitle")}
            </h3>
            <p className="text-sm text-gray-500 text-center mb-6 leading-relaxed">
              {t("modals.screeningReports.sendConfirmMessage")}
            </p>
            <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>
      )}

      {viewReport && (
        <ViewReportModal
          isOpen={!!viewReport}
          onClose={() => setViewReport(null)}
          clientId={viewReport.clientId}
          screeningId={viewReport.screeningId}
          suicideRisk={viewReport.suicideRisk}
          clientName={clientName}
        />
      )}
    </>
  );
}
