'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useAuthStore } from '@/stores/authStore';
import { Users, Stethoscope, CalendarCheck } from 'lucide-react';

export default function DoctorSummaryCards() {
  const user = useAuthStore((state) => state.user);
  const doctorId = user?.id;

  const [stats, setStats] = useState({
    patients: 0,
    consultations: 0,
    upcoming: 0,
  });

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchStats = async () => {
      if (!doctorId) return;

      try {
        const res = await fetch(`/api/consultations/stats/doctor/${doctorId}`);
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Failed to fetch doctor stats');

        setStats({
          patients: data.totalPatients || 0,
          consultations: data.totalConsultations || 0,
          upcoming: data.upcomingAppointments || 0,
        });
      } catch (err) {
        console.error(err);
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
  }, [doctorId]);

  const displayStats = [
    { name: 'patients', label: 'My Patients', count: stats.patients, icon: Users, color: 'bg-blue-500' },
    { name: 'consultations', label: 'Consultations Done', count: stats.consultations, icon: Stethoscope, color: 'bg-green-500' },
    { name: 'consultations', label: 'Upcoming Appointments', count: stats.upcoming, icon: CalendarCheck, color: 'bg-yellow-500' },
  ];

  if (loading) return <p className="text-sm text-gray-500">Loading doctor stats...</p>;
  if (error) return <p className="text-sm text-red-500">Error: {error}</p>;

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
      {displayStats.map((stat) => {
        const Icon = stat.icon;
        return (
          <Link href={`/dashboard/doctor/${stat.name}`} key={stat.label}>
            <div
              className={`text-white rounded-lg shadow p-4 cursor-pointer transition hover:scale-105 ${stat.color}`}
            >
              <div className="flex items-center gap-2 mb-2">
                <Icon className="w-5 h-5 opacity-90" />
                <h3 className="text-sm opacity-80">{stat.label}</h3>
              </div>
              <p className="text-2xl font-bold">{stat.count}</p>
            </div>
          </Link>
        );
      })}
    </div>
  );
}
