'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import SidebarLayout from '../components/sidebar-layout';
import ProtectedRoute from '../protected-route';
import { useTranslations } from '../hooks/useTranslations';
import { 
  Eye, 
  Plus, 
  Search, 
  Filter,
  Calendar,
  User,
  ChevronRight,
  FileText,
  Clock,
  Glasses,
  Activity
} from 'lucide-react';

interface Examination {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
  };
  doctorId: {
    name: string;
  };
  examDate: string;
  chiefComplaint: string;
  visualAcuity: {
    corrected: {
      distance: { OD: string; OS: string };
    };
  };
  iop: {
    OD: number;
    OS: number;
  };
  diagnosis: { description: string; eye: string }[];
}

export default function EyeExamPage() {
  const { t } = useTranslations();
  const [examinations, setExaminations] = useState<Examination[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [dateFilter, setDateFilter] = useState('');

  useEffect(() => {
    fetchExaminations();
  }, []);

  const fetchExaminations = async () => {
    try {
      setIsLoading(true);
      const params = new URLSearchParams();
      if (dateFilter) params.append('startDate', dateFilter);
      
      const response = await fetch(`/api/eye-exam?${params.toString()}`);
      const data = await response.json();
      setExaminations(data.examinations || []);
    } catch (error) {
      console.error('Error fetching examinations:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const filteredExaminations = examinations.filter(exam => {
    if (!searchTerm) return true;
    const search = searchTerm.toLowerCase();
    return (
      exam.patientId?.name?.toLowerCase().includes(search) ||
      exam.patientId?.patientId?.toLowerCase().includes(search) ||
      exam.chiefComplaint?.toLowerCase().includes(search)
    );
  });

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('eyeExam.title')} description={t('eyeExam.description')}>
        <div className="space-y-6">
          {/* Header with Quick Stats */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-blue-100 text-sm">Today's Exams</p>
                  <p className="text-3xl font-bold mt-1">{examinations.filter(e => 
                    new Date(e.examDate).toDateString() === new Date().toDateString()
                  ).length}</p>
                </div>
                <Eye className="h-10 w-10 text-blue-200" />
              </div>
            </div>
            
            <div className="bg-gradient-to-br from-green-500 to-green-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-green-100 text-sm">This Week</p>
                  <p className="text-3xl font-bold mt-1">{examinations.filter(e => {
                    const examDate = new Date(e.examDate);
                    const weekAgo = new Date();
                    weekAgo.setDate(weekAgo.getDate() - 7);
                    return examDate >= weekAgo;
                  }).length}</p>
                </div>
                <Calendar className="h-10 w-10 text-green-200" />
              </div>
            </div>
            
            <div className="bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-purple-100 text-sm">High IOP Cases</p>
                  <p className="text-3xl font-bold mt-1">{examinations.filter(e => 
                    e.iop?.OD > 21 || e.iop?.OS > 21
                  ).length}</p>
                </div>
                <Activity className="h-10 w-10 text-purple-200" />
              </div>
            </div>
            
            <div className="bg-gradient-to-br from-amber-500 to-amber-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-amber-100 text-sm">Total Records</p>
                  <p className="text-3xl font-bold mt-1">{examinations.length}</p>
                </div>
                <FileText className="h-10 w-10 text-amber-200" />
              </div>
            </div>
          </div>

          {/* Search and Actions Bar */}
          <div className="bg-white rounded-xl shadow-sm p-4 border border-gray-100">
            <div className="flex flex-col md:flex-row gap-4 items-center justify-between">
              <div className="flex flex-1 gap-4 w-full md:w-auto">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <input
                    type="text"
                    placeholder={t('eyeExam.searchPlaceholder')}
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
                <div className="relative">
                  <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
                  <input
                    type="date"
                    value={dateFilter}
                    onChange={(e) => setDateFilter(e.target.value)}
                    className="pl-10 pr-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  />
                </div>
              </div>
              
              <Link
                href="/eye-exam/new"
                className="flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium"
              >
                <Plus className="h-5 w-5" />
                {t('eyeExam.newExam')}
              </Link>
            </div>
          </div>

          {/* Examinations List */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            {isLoading ? (
              <div className="p-8 text-center">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
                <p className="mt-4 text-gray-500">Loading examinations...</p>
              </div>
            ) : filteredExaminations.length === 0 ? (
              <div className="p-12 text-center">
                <Eye className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">{t('eyeExam.noResults')}</h3>
                <p className="text-gray-500 mb-6">Start by creating a new eye examination</p>
                <Link
                  href="/eye-exam/new"
                  className="inline-flex items-center gap-2 px-5 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  <Plus className="h-5 w-5" />
                  {t('eyeExam.newExam')}
                </Link>
              </div>
            ) : (
              <div className="divide-y divide-gray-100">
                {filteredExaminations.map((exam) => (
                  <Link
                    key={exam._id}
                    href={`/eye-exam/${exam._id}`}
                    className="flex items-center justify-between p-5 hover:bg-gray-50 transition-colors"
                  >
                    <div className="flex items-center gap-4">
                      <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center">
                        <User className="h-6 w-6 text-blue-600" />
                      </div>
                      <div>
                        <h3 className="font-semibold text-gray-900">{exam.patientId?.name}</h3>
                        <p className="text-sm text-gray-500">ID: {exam.patientId?.patientId}</p>
                        <p className="text-sm text-gray-600 mt-1">{exam.chiefComplaint}</p>
                      </div>
                    </div>
                    
                    <div className="flex items-center gap-8">
                      <div className="text-center">
                        <p className="text-xs text-gray-500 uppercase tracking-wide">VA (BCVA)</p>
                        <p className="font-mono text-sm mt-1">
                          OD: {exam.visualAcuity?.corrected?.distance?.OD || '-'} | 
                          OS: {exam.visualAcuity?.corrected?.distance?.OS || '-'}
                        </p>
                      </div>
                      
                      <div className="text-center">
                        <p className="text-xs text-gray-500 uppercase tracking-wide">IOP</p>
                        <p className={`font-mono text-sm mt-1 ${
                          (exam.iop?.OD > 21 || exam.iop?.OS > 21) ? 'text-red-600 font-bold' : ''
                        }`}>
                          OD: {exam.iop?.OD || '-'} | OS: {exam.iop?.OS || '-'}
                        </p>
                      </div>
                      
                      <div className="text-right">
                        <div className="flex items-center gap-2 text-gray-500 text-sm">
                          <Clock className="h-4 w-4" />
                          {new Date(exam.examDate).toLocaleDateString()}
                        </div>
                        <p className="text-sm text-gray-500 mt-1">
                          Dr. {exam.doctorId?.name}
                        </p>
                      </div>
                      
                      <ChevronRight className="h-5 w-5 text-gray-400" />
                    </div>
                  </Link>
                ))}
              </div>
            )}
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
