'use client';

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

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

  const [stats, setStats] = useState({
    total: 0,
    pending: 0,
    completed: 0,
  });

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

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

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

        setStats({
          total: data.total || 0,
          pending: data.pending || 0,
          completed: data.completed || 0,
        });
      } catch (err) {
        console.error(err);
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    fetchStats();
  }, [labId]);

  const colors = ['bg-blue-500', 'bg-yellow-500', 'bg-green-500'];
  const labels = [
    { key: 'total', label: 'Total Tests', name: 'test-results', icon: FileText },
    { key: 'pending', label: 'Pending Results', name: 'test-results', icon: Clock },
    { key: 'completed', label: 'Completed Tests', name: 'test-results', icon: CheckCircle },
  ];

  if (loading) {
    return <p className="text-sm text-gray-500">Loading lab 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">
      {labels.map((item, index) => {
        const Icon = item.icon;
        return (
          <Link href={`/dashboard/lab/${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>
              <p className="text-2xl font-bold">{stats[item.key]}</p>
            </div>
          </Link>
        );
      })}
    </div>
  );
}
