"use client";

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

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

export default function ScreensCompletedModal({
  isOpen,
  onClose,
}: ScreensCompletedModalProps) {
  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 completed screenings from API
  const { data: response, isLoading } = usePractitionerDashboardControllerGetCompletedScreeningsV1(
    { page: 1, limit: 100 },
    { query: { enabled: isOpen } }
  );

  const completedScreenings: CompletedScreeningData[] = (response as any)?.data || [];

  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.screensCompleted.highRisk");
    }
    if (normalizedRisk?.includes("moderate")) {
      return t("modals.screensCompleted.moderateRisk");
    }
    if (normalizedRisk?.includes("mild")) {
      return t("modals.screensCompleted.mildRisk");
    }
    if (normalizedRisk?.includes("low")) {
      return t("modals.screensCompleted.lowRisk");
    }
    return risk || "-";
  };

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


  const ViewIcon = () => (
    <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>
  );

  const DownloadIcon = () => (
    <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>
  );

  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-[#22C55E]">{t("modals.screensCompleted.title")}</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">
                <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-200 min-w-[180px]">{t("modals.screensCompleted.clientName")}</th>
                <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.screensCompleted.mobileNumber")}</th>
                <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.screensCompleted.gender")}</th>
                <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.screensCompleted.age")}</th>
                <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.screensCompleted.suicideRiskCategory")}</th>
                <th className="text-center py-4 px-4 text-sm font-medium text-gray-500">{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>
              ) : completedScreenings.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-8 text-center text-gray-500">
                    {t("modals.screensCompleted.noData")}
                  </td>
                </tr>
              ) : (
                completedScreenings.map((screening, index) => (
                  <tr key={screening.screening_id} className={`${index !== completedScreenings.length - 1 ? 'border-b border-gray-200' : ''} hover:bg-gray-50/50 transition`}>
                    <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">{screening.client_name}</p>
                          <p className="text-sm text-gray-500">{screening.client_email || "-"}</p>
                        </div>
                      </div>
                    </td>
                    <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-200">{screening.mobile_number || "-"}</td>
                    <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-200">{(screening as any).gender || "-"}</td>
                    <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-200">{(screening as any).age || "-"}</td>
                    <td className="py-4 px-4 border-r border-gray-200">
                      <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 bg-current"></span>
                        {getRiskLabel(screening.suicide_risk_category)}
                      </span>
                    </td>
                    <td className="py-4 px-4">
                      <div className="flex items-center justify-center gap-3">
                        <button
                          onClick={() => handleViewReport(screening.client_id, screening.screening_id, screening.suicide_risk_category, screening.client_name, (screening as any).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"
                          title="View Report"
                        >
                          <ViewIcon />
                        </button>
                        <button
                          onClick={() => { setAutoDownloadClientId(screening.client_id); setAutoDownloadScreeningId(screening.screening_id); }}
                          disabled={autoDownloadScreeningId === screening.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"
                          title="Download"
                        >
                          {autoDownloadScreeningId === screening.screening_id ? (
                            <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[#3B9EC9]"></div>
                          ) : (
                            <DownloadIcon />
                          )}
                        </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}
      />

    </>
  );
}
