"use client";

import { useState } from "react";
import Modal from "@/components/Modal";
import { useTranslations } from "next-intl";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { customInstance } from "@/config/axios";
import { toast } from "react-hot-toast";
import { getDashboardControllerGetDashboardStatsV1QueryKey } from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import {
  usePractitionerDashboardControllerGetPendingScreeningsV1,
  getPractitionerDashboardControllerGetPendingScreeningsV1QueryKey,
} from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import { useClientsControllerSendReminderV1 } from "@/api/user/practitioner-clients/practitioner-clients";
import { PendingScreeningData } from "@/api/user/generated.schemas";
import ReminderSentModal from "./ReminderSentModal";

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

export default function PendingScreenModal({
  isOpen,
  onClose,
}: PendingScreenModalProps) {
  const t = useTranslations("practitioner");
  const queryClient = useQueryClient();
  const [sendingReminderId, setSendingReminderId] = useState<number | null>(null);
  const [reminderSentOpen, setReminderSentOpen] = useState(false);

  // Fetch pending screenings from API
  const { data: response, isLoading } = useQuery({
    queryKey: ['/v1/practitioner/dashboard/pending-screenings', { page: 1, limit: 100 }],
    queryFn: () => customInstance<{ data: PendingScreeningData[] }>({
      url: '/v1/practitioner/dashboard/pending-screenings',
      method: 'GET',
      params: { page: 1, limit: 100 },
    }),
    enabled: isOpen,
  });

  const pendingScreenings: PendingScreeningData[] = (response as any)?.data?.data || (response as any)?.data || [];

  // Send reminder mutation
  const { mutate: sendReminder } = useClientsControllerSendReminderV1({
    mutation: {
      onSuccess: () => {
        setSendingReminderId(null);
        setReminderSentOpen(true);
        queryClient.invalidateQueries({ queryKey: ['/v1/practitioner/dashboard/pending-screenings'] });
        queryClient.invalidateQueries({ queryKey: getDashboardControllerGetDashboardStatsV1QueryKey() });
      },
      onError: (error: any) => {
        toast.error(error?.response?.data?.message || t("modals.pendingScreen.reminderError"));
        setSendingReminderId(null);
      },
    },
  });

  const handleSendReminder = (clientId: number, screeningId: number) => {
    setSendingReminderId(screeningId);
    sendReminder({ id: clientId });
  };

  const ClockIcon = () => (
    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z" />
    </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-[#D4A017]">{t("modals.pendingScreen.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-[200px]">{t("modals.pendingScreen.clientName")}</th>
                <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.pendingScreen.mobileNumber")}</th>
                <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.pendingScreen.gender")}</th>
                <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-200">{t("modals.pendingScreen.age")}</th>
                <th className="text-center py-4 px-4 text-sm font-medium text-gray-500">{t("modals.pendingScreen.reminder")}</th>
              </tr>
            </thead>
            <tbody>
              {isLoading ? (
                <tr>
                  <td colSpan={5} 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>
              ) : pendingScreenings.length === 0 ? (
                <tr>
                  <td colSpan={5} className="py-8 text-center text-gray-500">
                    {t("modals.pendingScreen.noData")}
                  </td>
                </tr>
              ) : (
                pendingScreenings.map((screening, index) => (
                  <tr key={screening.screening_id} className={`${index !== pendingScreenings.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">
                      <div className="flex justify-center">
                        <button
                          onClick={() => handleSendReminder(screening.client_id, screening.screening_id)}
                          disabled={sendingReminderId === screening.screening_id}
                          className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          {sendingReminderId === screening.screening_id ? (
                            <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
                          ) : (
                            <ClockIcon />
                          )}
                          {t("modals.pendingScreen.reminder")}
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Reminder Sent Modal */}
      <ReminderSentModal
        isOpen={reminderSentOpen}
        onClose={() => setReminderSentOpen(false)}
      />
    </Modal>
  );
}
