"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations, useLocale } from "next-intl";
import { useGetScreenings } from "@/api/user/individual-dashboard/individual-dashboard";
import { useProfile } from "@/api/user/user-profile/user-profile";
import ScreeningReport from "@/components/individual/ScreeningReport";
import Modal from "@/components/Modal";

interface Screening {
  uuid: string;
  status: string;
  started_at: string | null;
  completed_at: string | null;
  created_at: string;
  is_paid: boolean;
  is_therapist_invited?: boolean;
  report_shared_with_client?: boolean;
  suicide_risk_category?: string;
  highest_risk?: string;
}

export default function IndividualDashboard() {
  const router = useRouter();
  const t = useTranslations("individual");
  const locale = useLocale();
  const [currentPage, setCurrentPage] = useState(1);
  const [viewingIsPaid, setViewingIsPaid] = useState<boolean>(true);
  const [viewingScreeningUuid, setViewingScreeningUuid] = useState<string | null>(null);
  const [autoDownloadUuid, setAutoDownloadUuid] = useState<string | null>(null);
  const itemsPerPage = 10;
  const { data: profileData } = useProfile();
  const userName = profileData?.data?.user?.name?.split(" ")[0] || "User";

  const { data: screeningsData, isLoading } = useGetScreenings({
    page: currentPage,
    limit: itemsPerPage,
  }, {
    query: { staleTime: 0, refetchOnMount: true, refetchOnWindowFocus: true },
  }) as { data: any; isLoading: boolean };

  const raw = screeningsData as any;
  const allScreenings: Screening[] =
    Array.isArray(raw?.data?.screenings) ? raw.data.screenings :
    Array.isArray(raw?.screenings) ? raw.screenings :
    Array.isArray(raw?.data?.data) ? raw.data.data :
    Array.isArray(raw?.data) ? raw.data :
    Array.isArray(raw) ? raw : [];

  const screenings = allScreenings.filter((s: Screening) => {
    if (!s.is_therapist_invited) return true;
    if (s.status !== "completed") return true;
    return s.report_shared_with_client === true;
  });
  const pagination = raw?.data?.pagination || raw?.pagination || raw?.data?.meta || raw?.meta || { total: 0, totalPages: 1 };
  const totalPages = pagination.totalPages || pagination.total_pages || pagination.last_page || 1;

  const handleViewScreening = (uuid: string, isPaid: boolean) => {
    setViewingIsPaid(isPaid);
    setViewingScreeningUuid(uuid);
  };

  const handleContinueScreening = (uuid: string, isPaid: boolean = true, isTherapistInvited: boolean = false) => {
    if (!isPaid || isTherapistInvited) {
      router.push(`/individual/screening/${uuid}/questions?source=assigned`);
    } else {
      router.push(`/individual/screening/${uuid}/questions?source=paid`);
    }
  };

  const handleDownloadScreening = (uuid: string, isPaid: boolean) => {
    setViewingIsPaid(isPaid);
    setAutoDownloadUuid(uuid);
  };

  const handleStartScreening = () => {
    router.push("/individual/screening");
  };

  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    const total = totalPages || 1;
    if (total <= 7) {
      for (let i = 1; i <= total; i++) pages.push(i);
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, "...", total - 1, total);
      } else if (currentPage >= total - 2) {
        pages.push(1, 2, "...", total - 2, total - 1, total);
      } else {
        pages.push(1, "...", currentPage - 1, currentPage, currentPage + 1, "...", total);
      }
    }
    return pages;
  };

  return (
    <>
      <main className="pt-20 pb-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          {/* Welcome Section */}
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-8">
            <div>
              <h1 className="text-2xl sm:text-3xl font-semibold text-gray-900">
                {t("dashboard.welcomeBack")} {userName}
              </h1>
              <p className="mt-1 text-sm text-gray-500">
                {t("dashboard.subtitle")}
              </p>
            </div>
            <button
              onClick={handleStartScreening}
              className="mt-4 sm:mt-0 px-6 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 transition cursor-pointer"
            >
              {t("dashboard.startScreening")}
            </button>
          </div>

          {/* Screening Table Card */}
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100">
            <div className="p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4">
                {t("dashboard.yourScreening")}
              </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 w-20 border-r border-gray-200">
                        {t("dashboard.no")}
                      </th>
                      <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">
                        {t("dashboard.screeningDate")}
                      </th>
                      <th className="text-left py-3 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">
                        {t("dashboard.status")}
                      </th>
                      <th className="text-center py-3 px-4 text-sm font-medium text-gray-500 w-32">
                        {t("dashboard.action")}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {isLoading ? (
                      <tr>
                        <td colSpan={3} className="py-8 text-center text-gray-500">
                          {t("dashboard.loadingScreenings")}
                        </td>
                      </tr>
                    ) : screenings.length === 0 ? (
                      <tr>
                        <td colSpan={3} className="py-8 text-center text-gray-500">
                          {t("dashboard.noScreeningsFound")}
                        </td>
                      </tr>
                    ) : (
                      screenings.map((screening, index) => (
                        <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">
                            {(currentPage - 1) * itemsPerPage + index + 1}
                          </td>
                          <td className="py-4 px-4 text-sm text-gray-900 border-r border-gray-200">
                            {new Date(screening.completed_at || screening.created_at).toLocaleDateString(locale === "es" ? "es-ES" : "en-GB", {
                              day: "numeric",
                              month: "short",
                              year: "numeric",
                            })}
                          </td>
                          <td className="py-4 px-4 border-r border-gray-200">
                            {screening.status === "completed" ? (
                              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">
                                {t("dashboard.statusCompleted")}
                              </span>
                            ) : screening.status === "in_progress" ? (
                              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700">
                                {t("dashboard.statusInProgress")}
                              </span>
                            ) : (
                              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-700">
                                {t("dashboard.statusPending")}
                              </span>
                            )}
                          </td>
                          <td className="py-4 px-4">
                            <div className="flex items-center justify-center gap-2">
                              {screening.status === "pending" && (
                                <button
                                  onClick={() => handleContinueScreening(screening.uuid, screening.is_paid, screening.is_therapist_invited)}
                                  className="px-4 py-1.5 text-xs font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
                                  title={t("dashboard.startScreening")}
                                >
                                  {t("dashboard.start")}
                                </button>
                              )}
                              {screening.status === "in_progress" && (
                                <button
                                  onClick={() => handleContinueScreening(screening.uuid, screening.is_paid, screening.is_therapist_invited)}
                                  className="px-4 py-1.5 text-xs font-medium text-white bg-green-600 rounded-full hover:bg-green-700 transition cursor-pointer"
                                  title={t("dashboard.continueScreeningTitle")}
                                >
                                  {t("dashboard.continue")}
                                </button>
                              )}
                              {screening.status === "completed" && (
                                <>
                                  <button
                                    onClick={() => handleViewScreening(screening.uuid, screening.is_paid)}
                                    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={t("dashboard.viewResults")}
                                  >
                                    <svg className="w-4 h-4" 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>
                                  <button
                                    onClick={() => handleDownloadScreening(screening.uuid, screening.is_paid)}
                                    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={t("dashboard.downloadReport")}
                                  >
                                    <svg className="w-4 h-4" 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>
                                </>
                              )}
                            </div>
                          </td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>

            {totalPages > 1 && (
              <div className="flex items-center justify-between px-6 py-4 border-t border-gray-100">
                <button
                  onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                  disabled={currentPage === 1}
                  className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition cursor-pointer"
                >
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
                  </svg>
                  {t("subscription.previous")}
                </button>
                <div className="hidden sm:flex items-center gap-1">
                  {getPageNumbers().map((page, index) =>
                    page === "..." ? (
                      <span key={`ellipsis-${index}`} className="px-3 py-2 text-sm text-gray-500">...</span>
                    ) : (
                      <button
                        key={page}
                        onClick={() => setCurrentPage(page as number)}
                        className={`w-9 h-9 flex items-center justify-center text-sm font-medium rounded-lg transition cursor-pointer ${
                          currentPage === page ? "bg-gray-100 text-gray-900" : "text-gray-600 hover:bg-gray-50"
                        }`}
                      >
                        {page}
                      </button>
                    )
                  )}
                </div>
                <button
                  onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                  disabled={currentPage === totalPages}
                  className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition cursor-pointer"
                >
                  {t("subscription.next")}
                  <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
                  </svg>
                </button>
              </div>
            )}
          </div>
        </div>
      </main>

      <Modal isOpen={!!viewingScreeningUuid} onClose={() => setViewingScreeningUuid(null)} size="3xl">
        {viewingScreeningUuid && (
          <ScreeningReport
            screeningId={viewingScreeningUuid}
            isPaid={viewingIsPaid}
            isModal
            onClose={() => setViewingScreeningUuid(null)}
          />
        )}
      </Modal>

      {autoDownloadUuid && (
        <div style={{ position: "fixed", top: -9999, left: -9999, opacity: 0, pointerEvents: "none", zIndex: -1 }}>
          <ScreeningReport
            screeningId={autoDownloadUuid}
            isPaid={viewingIsPaid}
            autoDownload
            onClose={() => setAutoDownloadUuid(null)}
          />
        </div>
      )}
    </>
  );
}
