"use client";

import { Suspense, useEffect, useState } from "react";
import { useParams, useSearchParams } from "next/navigation";

interface AppointmentData {
  id: string;
  status: string;
  dateTime: string;
  treatment: string;
  clinic: string;
  patientName: string;
  duration: number;
}

function ConfirmContent() {
  const params = useParams();
  const searchParams = useSearchParams();
  const id = params.id as string;
  const token = searchParams.get("token");

  const [data, setData] = useState<AppointmentData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [confirmed, setConfirmed] = useState(false);
  const [alreadyHandled, setAlreadyHandled] = useState(false);

  useEffect(() => {
    async function load() {
      try {
        const detailRes = await fetch(`/api/confirm/${id}/details`);
        if (!detailRes.ok) {
          setError("Appointment not found");
          return;
        }
        const result = await detailRes.json();
        setData(result);

        if (["confirmed", "arrived", "in_progress", "completed"].includes(result.status)) {
          setAlreadyHandled(true);
          return;
        }
        if (["cancelled", "rescheduled", "no_show"].includes(result.status)) {
          setAlreadyHandled(true);
          return;
        }

        if (token && ["scheduled", "booked"].includes(result.status)) {
          const confirmRes = await fetch(`/api/confirm/${id}/action`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ token }),
          });

          if (confirmRes.ok) {
            setConfirmed(true);
            const refreshRes = await fetch(`/api/confirm/${id}/details`);
            if (refreshRes.ok) {
              const refreshed = await refreshRes.json();
              setData(refreshed);
            }
          }
        }
      } catch {
        setError("Something went wrong. Please try again.");
      } finally {
        setLoading(false);
      }
    }

    load();
  }, [id, token]);

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4" />
          <p className="text-gray-600 text-lg">Confirming your appointment...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-red-50 to-orange-100 flex items-center justify-center p-4">
        <div className="bg-white rounded-2xl shadow-xl p-6 sm:p-8 max-w-md w-full text-center">
          <div className="text-5xl mb-4">❌</div>
          <h1 className="text-xl sm:text-2xl font-bold text-gray-800 mb-2">Oops!</h1>
          <p className="text-gray-600 text-sm sm:text-base">{error}</p>
        </div>
      </div>
    );
  }

  if (!data) return null;

  const dt = new Date(data.dateTime);
  const dateStr = dt.toLocaleDateString("en-US", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });
  const timeStr = dt.toLocaleTimeString("en-US", {
    hour: "numeric",
    minute: "2-digit",
    hour12: true,
  });

  const statusColor = confirmed
    ? "from-green-50 to-emerald-100"
    : data.status === "confirmed"
    ? "from-green-50 to-emerald-100"
    : ["cancelled", "no_show", "rescheduled"].includes(data.status)
    ? "from-gray-50 to-gray-100"
    : "from-blue-50 to-indigo-100";

  const statusTitle = confirmed
    ? "Appointment Confirmed! 🎉"
    : data.status === "confirmed"
    ? "Already Confirmed ✅"
    : data.status === "completed"
    ? "Appointment Completed ✅"
    : data.status === "cancelled"
    ? "Appointment Cancelled"
    : data.status === "rescheduled"
    ? "Appointment Rescheduled"
    : data.status === "no_show"
    ? "Appointment Missed"
    : "Appointment Details";

  const statusMessage = confirmed
    ? "Your appointment has been successfully confirmed."
    : alreadyHandled
    ? `This appointment is ${data.status.replace("_", "-")}.`
    : "Review your appointment details below.";

  return (
    <div className={`min-h-screen bg-gradient-to-br ${statusColor} flex items-center justify-center p-4`}>
      <div className="bg-white rounded-2xl shadow-xl p-6 sm:p-8 max-w-md w-full">
        {/* Status Icon */}
        <div className="text-center mb-6">
          <div
            className={`inline-flex items-center justify-center w-16 h-16 sm:w-20 sm:h-20 rounded-full mb-4 ${
              confirmed || data.status === "confirmed" || data.status === "completed"
                ? "bg-green-100"
                : ["cancelled", "no_show", "rescheduled"].includes(data.status)
                ? "bg-gray-100"
                : "bg-blue-100"
            }`}
          >
            {confirmed || data.status === "confirmed" || data.status === "completed" ? (
              <svg className="w-8 h-8 sm:w-10 sm:h-10 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
              </svg>
            ) : ["cancelled", "no_show", "rescheduled"].includes(data.status) ? (
              <svg className="w-8 h-8 sm:w-10 sm:h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M6 18L18 6M6 6l12 12" />
              </svg>
            ) : (
              <svg className="w-8 h-8 sm:w-10 sm:h-10 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            )}
          </div>

          <h1 className="text-xl sm:text-2xl font-bold text-gray-800 mb-1">{statusTitle}</h1>
          <p className="text-gray-500 text-sm">{statusMessage}</p>
        </div>

        {/* Appointment Details */}
        <div className="bg-gray-50 rounded-xl p-4 sm:p-5 space-y-3 sm:space-y-4 mb-6">
          <div className="flex items-start gap-3">
            <span className="text-lg sm:text-xl">🏥</span>
            <div>
              <p className="text-[10px] sm:text-xs text-gray-400 uppercase tracking-wide">Clinic</p>
              <p className="text-sm sm:text-base text-gray-800 font-semibold">{data.clinic}</p>
            </div>
          </div>
          <div className="flex items-start gap-3">
            <span className="text-lg sm:text-xl">👤</span>
            <div>
              <p className="text-[10px] sm:text-xs text-gray-400 uppercase tracking-wide">Patient</p>
              <p className="text-sm sm:text-base text-gray-800 font-semibold">{data.patientName}</p>
            </div>
          </div>
          <div className="flex items-start gap-3">
            <span className="text-lg sm:text-xl">💆</span>
            <div>
              <p className="text-[10px] sm:text-xs text-gray-400 uppercase tracking-wide">Treatment</p>
              <p className="text-sm sm:text-base text-gray-800 font-semibold">{data.treatment}</p>
              <p className="text-gray-500 text-xs sm:text-sm">{data.duration} minutes</p>
            </div>
          </div>
          <div className="flex items-start gap-3">
            <span className="text-lg sm:text-xl">📅</span>
            <div>
              <p className="text-[10px] sm:text-xs text-gray-400 uppercase tracking-wide">Date</p>
              <p className="text-sm sm:text-base text-gray-800 font-semibold">{dateStr}</p>
            </div>
          </div>
          <div className="flex items-start gap-3">
            <span className="text-lg sm:text-xl">🕐</span>
            <div>
              <p className="text-[10px] sm:text-xs text-gray-400 uppercase tracking-wide">Time</p>
              <p className="text-sm sm:text-base text-gray-800 font-semibold">{timeStr}</p>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="text-center">
          {(confirmed || data.status === "confirmed") && (
            <p className="text-gray-500 text-xs sm:text-sm">📌 Please arrive 10 minutes early.</p>
          )}
          <p className="text-gray-400 text-[10px] sm:text-xs mt-2">
            Need to reschedule? Reply to our WhatsApp message.
          </p>
        </div>
      </div>
    </div>
  );
}

export default function ConfirmPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4" />
            <p className="text-gray-600 text-lg">Loading...</p>
          </div>
        </div>
      }
    >
      <ConfirmContent />
    </Suspense>
  );
}
