'use client';

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

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

  const [stats, setStats] = useState({
    doctorsConsulted: 0,
    upcomingAppointments: 0,
    completedReports: 0,
    pendingTests: 0,
    inProgressTests: 0,
    completedTests: 0,
    doctorCallouts: 0,
    pendingCallouts: 0,
    acceptedCallouts: 0,
    rejectedCallouts: 0,
  });

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

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

      try {
        const res = await fetch(`/api/lab-tests/stats/patient/${patientId}`);
        const data = await res.json();

        const resultscallout = await fetch(`/api/consultations/stats/callouts`);
        const calloutData = await resultscallout.json();
        console.log('Callout Data:', calloutData);

        if (!res.ok) throw new Error(data.error || 'Failed to fetch patient lab stats');

        const consultRes = await fetch(`/api/consultations/stats/patient/${patientId}`);
        const consultData = await consultRes.json();
        if (!consultRes.ok) throw new Error(consultData.error || 'Failed to fetch consultations');

        setStats({
          doctorsConsulted: consultData.totalDoctors || 0,
          upcomingAppointments: consultData.upcoming || 0,
          completedReports: data.completed || 0,
          pendingTests: data.pending || 0,
          inProgressTests: data.inProgress || 0,
          completedTests: data.completed || 0,
          doctorCallouts: calloutData.totalCallouts || 0,
          pendingCallouts: calloutData.pendingCallouts || 0,
          acceptedCallouts: calloutData.acceptedCallouts || 0,
          rejectedCallouts: calloutData.rejectedCallouts || 0,
        });
      } catch (err) {
        console.error('Error fetching patient stats:', err);
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
  }, [patientId]);

  const cardData = [
    { name: 'doctors', label: 'Doctors Consulted', key: 'doctorsConsulted', icon: Stethoscope },
    { name: 'appointments', label: 'Upcoming Appointments', key: 'upcomingAppointments', icon: CalendarClock },
    { name: 'test-results', label: 'Pending Lab Tests', key: 'pendingTests', icon: FileText },
    { name: 'test-results', label: 'In Progress Lab Tests', key: 'inProgressTests', icon: FileText },
    { name: 'test-results', label: 'Completed Lab Tests', key: 'completedTests', icon: FileText },
    { name: 'test-results', label: 'Medical Reports', key: 'completedReports', icon: FileText },
    { name: 'callouts', label: 'Total Doctor Callouts', key: 'doctorCallouts', icon: PhoneCall },
    { name: 'callouts', label: 'Pending Callouts', key: 'pendingCallouts', icon: PhoneCall },
    { name: 'callouts', label: 'Accepted Callouts', key: 'acceptedCallouts', icon: PhoneCall },
    { name: 'callouts', label: 'Rejected Callouts', key: 'rejectedCallouts', icon: PhoneCall },
  ];

  const colors = [
    'bg-blue-500',
    'bg-yellow-500',
    'bg-orange-500',
    'bg-indigo-500',
    'bg-green-500',
    'bg-purple-500',
    'bg-rose-500',
    'bg-teal-500',
    'bg-pink-500',
    'bg-red-500',
  ];

  if (loading) return <p className="text-sm text-gray-500">Loading patient 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">
      {cardData.map((item, index) => {
        const Icon = item.icon;
        return (
          <Link href={`/dashboard/patient/${item.name}`} key={item.key}>
            <div
              className={`text-white rounded-lg shadow p-4 cursor-pointer transition hover:scale-105 ${colors[index % colors.length]}`}
            >
              <div className="flex items-center gap-2 mb-2">
                <Icon className="w-5 h-5 opacity-90" />
                <h3 className="text-sm opacity-80">{item.label}</h3>
              </div>
              {stats[item.key] !== '' && (
                <p className="text-2xl font-bold">{stats[item.key]}</p>
              )}
            </div>
          </Link>
        );
      })}
    </div>
  );
}
