'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, 
  AlertTriangle,
  Calendar,
  User,
  ChevronRight,
  Activity,
  Camera,
  Brain,
  Clock,
  TrendingUp
} from 'lucide-react';

interface DRRecord {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    dateOfBirth: string;
  };
  diabetesType: string;
  diabetesDuration: number;
  currentStatus: {
    OD: { drLevel: string; dme: boolean };
    OS: { drLevel: string; dme: boolean };
  };
  metabolicControl: {
    lastHba1c: { value: number; date: string };
  };
  followUpSchedule: {
    nextScreening: string;
  };
  updatedAt: string;
}

interface Stats {
  total: number;
  noDR: number;
  mildNpdr: number;
  moderateNpdr: number;
  severeNpdr: number;
  pdr: number;
  dueForScreening: number;
}

export default function DRScreeningPage() {
  const { t } = useTranslations();
  const [records, setRecords] = useState<DRRecord[]>([]);
  const [stats, setStats] = useState<Stats | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [drLevelFilter, setDrLevelFilter] = useState('');
  const [showDueOnly, setShowDueOnly] = useState(false);

  useEffect(() => {
    fetchRecords();
  }, [drLevelFilter, showDueOnly]);

  const fetchRecords = async () => {
    try {
      setIsLoading(true);
      const params = new URLSearchParams();
      if (drLevelFilter) params.append('drLevel', drLevelFilter);
      if (showDueOnly) params.append('dueForScreening', 'true');
      
      const response = await fetch(`/api/dr-screening?${params.toString()}`);
      const data = await response.json();
      setRecords(data.records || []);
      setStats(data.stats || null);
    } 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 getDRLevelColor = (level: string) => {
    switch (level) {
      case 'none': return 'bg-green-100 text-green-700';
      case 'mild': return 'bg-yellow-100 text-yellow-700';
      case 'moderate': return 'bg-orange-100 text-orange-700';
      case 'severe': return 'bg-red-100 text-red-700';
      case 'pdr': return 'bg-red-200 text-red-800';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const getDRLevelLabel = (level: string) => {
    switch (level) {
      case 'none': return t('drScreening.grades.none');
      case 'mild': return t('drScreening.grades.mild');
      case 'moderate': return t('drScreening.grades.moderate');
      case 'severe': return t('drScreening.grades.severe');
      case 'pdr': return t('drScreening.grades.pdr');
      default: return level;
    }
  };

  const getWorstEye = (record: DRRecord) => {
    const levels = ['none', 'mild', 'moderate', 'severe', 'pdr'];
    const odLevel = levels.indexOf(record.currentStatus?.OD?.drLevel || 'none');
    const osLevel = levels.indexOf(record.currentStatus?.OS?.drLevel || 'none');
    return odLevel >= osLevel ? 'OD' : 'OS';
  };

  const isDueForScreening = (nextScreening: string) => {
    if (!nextScreening) return false;
    return new Date(nextScreening) <= new Date();
  };

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('drScreening.title')} description={t('drScreening.description')}>
        <div className="space-y-6">
          {/* Stats Cards */}
          {stats && (
            <div className="grid grid-cols-2 md:grid-cols-7 gap-4">
              <div className="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-4 text-white">
                <p className="text-blue-100 text-xs">Total Diabetics</p>
                <p className="text-2xl font-bold mt-1">{stats.total}</p>
              </div>
              <div className="bg-gradient-to-br from-green-500 to-green-600 rounded-xl p-4 text-white">
                <p className="text-green-100 text-xs">{t('drScreening.grades.none')}</p>
                <p className="text-2xl font-bold mt-1">{stats.noDR}</p>
              </div>
              <div className="bg-gradient-to-br from-yellow-500 to-yellow-600 rounded-xl p-4 text-white">
                <p className="text-yellow-100 text-xs">{t('drScreening.grades.mild')}</p>
                <p className="text-2xl font-bold mt-1">{stats.mildNpdr}</p>
              </div>
              <div className="bg-gradient-to-br from-orange-500 to-orange-600 rounded-xl p-4 text-white">
                <p className="text-orange-100 text-xs">{t('drScreening.grades.moderate')}</p>
                <p className="text-2xl font-bold mt-1">{stats.moderateNpdr}</p>
              </div>
              <div className="bg-gradient-to-br from-red-500 to-red-600 rounded-xl p-4 text-white">
                <p className="text-red-100 text-xs">{t('drScreening.grades.severe')}</p>
                <p className="text-2xl font-bold mt-1">{stats.severeNpdr}</p>
              </div>
              <div className="bg-gradient-to-br from-red-600 to-red-700 rounded-xl p-4 text-white">
                <p className="text-red-100 text-xs">{t('drScreening.grades.pdr')}</p>
                <p className="text-2xl font-bold mt-1">{stats.pdr}</p>
              </div>
              <div className={`rounded-xl p-4 text-white ${
                stats.dueForScreening > 0 
                  ? 'bg-gradient-to-br from-amber-500 to-amber-600' 
                  : 'bg-gradient-to-br from-gray-500 to-gray-600'
              }`}>
                <p className={`text-xs ${stats.dueForScreening > 0 ? 'text-amber-100' : 'text-gray-100'}`}>
                  Due Today
                </p>
                <p className="text-2xl font-bold mt-1">{stats.dueForScreening}</p>
              </div>
            </div>
          )}

          {/* AI Screening Banner */}
          <div className="bg-gradient-to-r from-purple-600 to-indigo-600 rounded-xl p-6 text-white">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-4">
                <div className="p-3 bg-white/20 rounded-xl">
                  <Brain className="h-8 w-8" />
                </div>
                <div>
                  <h3 className="text-xl font-bold">AI-Powered DR Detection</h3>
                  <p className="text-purple-100 mt-1">
                    Automated analysis of fundus images with instant grading
                  </p>
                </div>
              </div>
              <Link
                href="/dr-screening/ai-analysis"
                className="px-6 py-3 bg-white text-purple-600 rounded-lg font-medium hover:bg-purple-50 transition-colors"
              >
                Start AI Screening
              </Link>
            </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('drScreening.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-purple-500"
                  />
                </div>
                <select
                  value={drLevelFilter}
                  onChange={(e) => setDrLevelFilter(e.target.value)}
                  className="px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-purple-500"
                >
                  <option value="">{t('drScreening.allScreenings')}</option>
                  <option value="none">{t('drScreening.grades.none')}</option>
                  <option value="mild">{t('drScreening.grades.mild')}</option>
                  <option value="moderate">{t('drScreening.grades.moderate')}</option>
                  <option value="severe">{t('drScreening.grades.severe')}</option>
                  <option value="pdr">{t('drScreening.grades.pdr')}</option>
                </select>
                <label className="flex items-center gap-2 px-4 py-2.5 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50">
                  <input
                    type="checkbox"
                    checked={showDueOnly}
                    onChange={(e) => setShowDueOnly(e.target.checked)}
                    className="rounded text-purple-600"
                  />
                  <span className="text-sm text-gray-700">{t('drScreening.dueScreening')}</span>
                </label>
              </div>
              
              <Link
                href="/dr-screening/new"
                className="flex items-center gap-2 px-5 py-2.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors font-medium"
              >
                <Plus className="h-5 w-5" />
                New Patient
              </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-purple-600 mx-auto"></div>
                <p className="mt-4 text-gray-500">Loading records...</p>
              </div>
            ) : filteredRecords.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('drScreening.noResults')}</h3>
                <p className="text-gray-500 mb-6">{t('drScreening.description')}</p>
                <Link
                  href="/dr-screening/new"
                  className="inline-flex items-center gap-2 px-5 py-2.5 bg-purple-600 text-white rounded-lg hover:bg-purple-700"
                >
                  <Plus className="h-5 w-5" />
                  Add Patient
                </Link>
              </div>
            ) : (
              <div className="divide-y divide-gray-100">
                {filteredRecords.map((record) => {
                  const worstEye = getWorstEye(record);
                  const worstLevel = record.currentStatus?.[worstEye as 'OD' | 'OS']?.drLevel || 'none';
                  const hasDME = record.currentStatus?.OD?.dme || record.currentStatus?.OS?.dme;
                  const isDue = isDueForScreening(record.followUpSchedule?.nextScreening);
                  
                  return (
                    <Link
                      key={record._id}
                      href={`/dr-screening/${record._id}`}
                      className={`flex items-center justify-between p-5 hover:bg-gray-50 transition-colors ${
                        isDue ? 'bg-amber-50/50' : ''
                      }`}
                    >
                      <div className="flex items-center gap-4">
                        <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
                          worstLevel === 'pdr' || worstLevel === 'severe' 
                            ? 'bg-red-100' 
                            : worstLevel === 'moderate' 
                              ? 'bg-orange-100' 
                              : 'bg-green-100'
                        }`}>
                          <Eye className={`h-6 w-6 ${
                            worstLevel === 'pdr' || worstLevel === 'severe' 
                              ? 'text-red-600' 
                              : worstLevel === 'moderate' 
                                ? 'text-orange-600' 
                                : 'text-green-600'
                          }`} />
                        </div>
                        <div>
                          <div className="flex items-center gap-2">
                            <h3 className="font-semibold text-gray-900">{record.patientId?.name}</h3>
                            {isDue && (
                              <span className="px-2 py-0.5 bg-amber-500 text-white rounded text-xs font-medium">
                                DUE
                              </span>
                            )}
                          </div>
                          <p className="text-sm text-gray-500">
                            ID: {record.patientId?.patientId} | DM Duration: {record.diabetesDuration} years
                          </p>
                        </div>
                      </div>
                      
                      <div className="flex items-center gap-8">
                        <div className="text-center">
                          <p className="text-xs text-gray-500 uppercase tracking-wide">OD</p>
                          <span className={`inline-block mt-1 px-2 py-0.5 rounded text-xs font-medium ${
                            getDRLevelColor(record.currentStatus?.OD?.drLevel)
                          }`}>
                            {getDRLevelLabel(record.currentStatus?.OD?.drLevel)}
                          </span>
                          {record.currentStatus?.OD?.dme && (
                            <span className="block mt-1 text-xs text-red-600 font-medium">+DME</span>
                          )}
                        </div>
                        
                        <div className="text-center">
                          <p className="text-xs text-gray-500 uppercase tracking-wide">OS</p>
                          <span className={`inline-block mt-1 px-2 py-0.5 rounded text-xs font-medium ${
                            getDRLevelColor(record.currentStatus?.OS?.drLevel)
                          }`}>
                            {getDRLevelLabel(record.currentStatus?.OS?.drLevel)}
                          </span>
                          {record.currentStatus?.OS?.dme && (
                            <span className="block mt-1 text-xs text-red-600 font-medium">+DME</span>
                          )}
                        </div>
                        
                        <div className="text-center">
                          <p className="text-xs text-gray-500 uppercase tracking-wide">HbA1c</p>
                          <p className={`font-semibold mt-1 ${
                            (record.metabolicControl?.lastHba1c?.value || 0) > 7.5 
                              ? 'text-red-600' 
                              : 'text-green-600'
                          }`}>
                            {record.metabolicControl?.lastHba1c?.value || '-'}%
                          </p>
                        </div>
                        
                        <div className="text-right min-w-[100px]">
                          <p className="text-xs text-gray-500">{t('drScreening.tableHeaders.nextScreening')}</p>
                          <p className={`text-sm font-medium mt-1 ${
                            isDue ? 'text-amber-600' : 'text-gray-900'
                          }`}>
                            {record.followUpSchedule?.nextScreening 
                              ? new Date(record.followUpSchedule.nextScreening).toLocaleDateString()
                              : 'Not scheduled'}
                          </p>
                        </div>
                        
                        <ChevronRight className="h-5 w-5 text-gray-400" />
                      </div>
                    </Link>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
