'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 { 
  Activity, 
  Plus, 
  Search, 
  TrendingUp,
  TrendingDown,
  AlertCircle,
  Eye,
  User,
  ChevronRight,
  Calendar,
  Target,
  LineChart
} from 'lucide-react';

interface GlaucomaRecord {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    dateOfBirth: string;
  };
  glaucomaType: string;
  severity: string;
  affectedEyes: string;
  targetIOP: { OD: number; OS: number };
  progressionAnalysis: {
    overallStatus: string;
    iopControl: string;
  };
  iopHistory: { date: string; OD: number; OS: number }[];
  followUpSchedule: { nextVisit: string };
  currentMedications: { name: string }[];
  updatedAt: string;
}

export default function GlaucomaPage() {
  const { t } = useTranslations();
  const [records, setRecords] = useState<GlaucomaRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');

  useEffect(() => {
    fetchRecords();
  }, [typeFilter, statusFilter]);

  const fetchRecords = async () => {
    try {
      setIsLoading(true);
      const params = new URLSearchParams();
      if (typeFilter) params.append('glaucomaType', typeFilter);
      if (statusFilter) params.append('status', statusFilter);
      
      const response = await fetch(`/api/glaucoma?${params.toString()}`);
      const data = await response.json();
      setRecords(data.records || []);
    } catch (error) {
      console.error('Error fetching records:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const filteredRecords = records.filter(record => {
    if (!searchTerm) return true;
    const search = searchTerm.toLowerCase();
    return (
      record.patientId?.name?.toLowerCase().includes(search) ||
      record.patientId?.patientId?.toLowerCase().includes(search)
    );
  });

  const getLastIOP = (record: GlaucomaRecord) => {
    if (!record.iopHistory || record.iopHistory.length === 0) return null;
    return record.iopHistory[record.iopHistory.length - 1];
  };

  const isIOPControlled = (record: GlaucomaRecord) => {
    const lastIOP = getLastIOP(record);
    if (!lastIOP || !record.targetIOP) return null;
    return lastIOP.OD <= record.targetIOP.OD && lastIOP.OS <= record.targetIOP.OS;
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'stable': return 'bg-green-100 text-green-700';
      case 'suspectedProgression': return 'bg-yellow-100 text-yellow-700';
      case 'definiteProgression': return 'bg-red-100 text-red-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'poag': return 'Primary Open-Angle';
      case 'pacg': return 'Primary Angle-Closure';
      case 'ntg': return 'Normal-Tension';
      case 'secondary': return 'Secondary';
      case 'congenital': return 'Congenital';
      case 'suspect': return 'Glaucoma Suspect';
      case 'ohT': return 'Ocular Hypertension';
      default: return type;
    }
  };

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('glaucomaCenter.title')} description={t('glaucomaCenter.description')}>
        <div className="space-y-6">
          {/* Stats Cards */}
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div className="bg-gradient-to-br from-indigo-500 to-indigo-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-indigo-100 text-sm">Total Patients</p>
                  <p className="text-3xl font-bold mt-1">{records.length}</p>
                </div>
                <Eye className="h-10 w-10 text-indigo-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">Stable</p>
                  <p className="text-3xl font-bold mt-1">
                    {records.filter(r => r.progressionAnalysis?.overallStatus === 'stable').length}
                  </p>
                </div>
                <TrendingUp className="h-10 w-10 text-green-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">Progressing</p>
                  <p className="text-3xl font-bold mt-1">
                    {records.filter(r => 
                      r.progressionAnalysis?.overallStatus === 'suspectedProgression' ||
                      r.progressionAnalysis?.overallStatus === 'definiteProgression'
                    ).length}
                  </p>
                </div>
                <TrendingDown className="h-10 w-10 text-amber-200" />
              </div>
            </div>
            
            <div className="bg-gradient-to-br from-red-500 to-red-600 rounded-xl p-5 text-white">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-red-100 text-sm">High IOP</p>
                  <p className="text-3xl font-bold mt-1">
                    {records.filter(r => {
                      const lastIOP = getLastIOP(r);
                      return lastIOP && (lastIOP.OD > 21 || lastIOP.OS > 21);
                    }).length}
                  </p>
                </div>
                <AlertCircle className="h-10 w-10 text-red-200" />
              </div>
            </div>
          </div>

          {/* Search and Filters */}
          <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">
                <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('glaucomaCenter.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-indigo-500"
                  />
                </div>
                <select
                  value={typeFilter}
                  onChange={(e) => setTypeFilter(e.target.value)}
                  className="px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
                >
                  <option value="">All Types</option>
                  <option value="poag">POAG</option>
                  <option value="pacg">PACG</option>
                  <option value="ntg">NTG</option>
                  <option value="secondary">Secondary</option>
                  <option value="suspect">Suspect</option>
                  <option value="ohT">OHT</option>
                </select>
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-indigo-500"
                >
                  <option value="">All Status</option>
                  <option value="stable">Stable</option>
                  <option value="suspectedProgression">Suspected Progression</option>
                  <option value="definiteProgression">Definite Progression</option>
                </select>
              </div>
              
              <Link
                href="/glaucoma/new"
                className="flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors font-medium"
              >
                <Plus className="h-5 w-5" />
                {t('glaucomaCenter.newRecord')}
              </Link>
            </div>
          </div>

          {/* Records 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-indigo-600 mx-auto"></div>
                <p className="mt-4 text-gray-500">Loading glaucoma records...</p>
              </div>
            ) : filteredRecords.length === 0 ? (
              <div className="p-12 text-center">
                <Activity className="h-16 w-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-900 mb-2">{t('glaucomaCenter.noResults')}</h3>
                <p className="text-gray-500 mb-6">{t('glaucomaCenter.description')}</p>
                <Link
                  href="/glaucoma/new"
                  className="inline-flex items-center gap-2 px-5 py-2.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors"
                >
                  <Plus className="h-5 w-5" />
                  {t('glaucomaCenter.newRecord')}
                </Link>
              </div>
            ) : (
              <div className="divide-y divide-gray-100">
                {filteredRecords.map((record) => {
                  const lastIOP = getLastIOP(record);
                  const controlled = isIOPControlled(record);
                  
                  return (
                    <Link
                      key={record._id}
                      href={`/glaucoma/${record._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 rounded-full flex items-center justify-center ${
                          controlled === true ? 'bg-green-100' : 
                          controlled === false ? 'bg-red-100' : 'bg-gray-100'
                        }`}>
                          <Eye className={`h-6 w-6 ${
                            controlled === true ? 'text-green-600' : 
                            controlled === false ? 'text-red-600' : 'text-gray-600'
                          }`} />
                        </div>
                        <div>
                          <h3 className="font-semibold text-gray-900">{record.patientId?.name}</h3>
                          <p className="text-sm text-gray-500">ID: {record.patientId?.patientId}</p>
                          <div className="flex items-center gap-2 mt-1">
                            <span className="px-2 py-0.5 bg-indigo-100 text-indigo-700 rounded text-xs font-medium">
                              {getTypeLabel(record.glaucomaType)}
                            </span>
                            <span className={`px-2 py-0.5 rounded text-xs font-medium ${
                              getStatusColor(record.progressionAnalysis?.overallStatus)
                            }`}>
                              {record.progressionAnalysis?.overallStatus || 'Unknown'}
                            </span>
                          </div>
                        </div>
                      </div>
                      
                      <div className="flex items-center gap-8">
                        <div className="text-center">
                          <p className="text-xs text-gray-500 uppercase tracking-wide">Last IOP</p>
                          {lastIOP ? (
                            <p className={`font-mono text-sm mt-1 ${
                              (lastIOP.OD > 21 || lastIOP.OS > 21) ? 'text-red-600 font-bold' : ''
                            }`}>
                              OD: {lastIOP.OD} | OS: {lastIOP.OS}
                            </p>
                          ) : (
                            <p className="text-sm text-gray-400 mt-1">No data</p>
                          )}
                        </div>
                        
                        <div className="text-center">
                          <p className="text-xs text-gray-500 uppercase tracking-wide">Target</p>
                          <p className="font-mono text-sm mt-1 text-indigo-600">
                            OD: {record.targetIOP?.OD || '-'} | OS: {record.targetIOP?.OS || '-'}
                          </p>
                        </div>
                        
                        <div className="text-center">
                          <p className="text-xs text-gray-500 uppercase tracking-wide">Medications</p>
                          <p className="text-sm mt-1">
                            {record.currentMedications?.length || 0} drops
                          </p>
                        </div>
                        
                        <div className="text-right min-w-[100px]">
                          <p className="text-xs text-gray-500">Next Visit</p>
                          <p className="text-sm font-medium text-gray-900 mt-1">
                            {record.followUpSchedule?.nextVisit 
                              ? new Date(record.followUpSchedule.nextVisit).toLocaleDateString()
                              : 'Not scheduled'}
                          </p>
                        </div>
                        
                        <ChevronRight className="h-5 w-5 text-gray-400" />
                      </div>
                    </Link>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
