'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import SidebarLayout from '../../components/sidebar-layout';
import { useTranslations } from '../../hooks/useTranslations';
import { 
  Activity, 
  TrendingUp, 
  TrendingDown,
  Search,
  Filter,
  ArrowLeft,
  Plus,
  Eye
} from 'lucide-react';

interface IOPRecord {
  patientId: {
    _id: string;
    name: string;
    patientId: string;
  };
  _id: string;
  iopHistory: {
    date: string;
    OD: number;
    OS: number;
    method: string;
    time: string;
  }[];
  targetIOP: { OD: number; OS: number };
  glaucomaType: string;
}

export default function IOPTrackingPage() {
  const { t } = useTranslations();
  const [records, setRecords] = useState<IOPRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [filterStatus, setFilterStatus] = useState('all');

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

  const fetchRecords = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/glaucoma');
      if (response.ok) {
        const data = await response.json();
        setRecords(data.records || []);
      }
    } catch (error) {
      console.error('Error fetching records:', error);
    } finally {
      setIsLoading(false);
    }
  };

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

  const getIOPStatus = (current: number, target: number) => {
    if (current <= target) return 'controlled';
    if (current <= target + 3) return 'borderline';
    return 'uncontrolled';
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'controlled':
        return <span className="px-2 py-1 text-xs font-medium rounded-full bg-green-100 text-green-700">{t('glaucomaCenter.controlled')}</span>;
      case 'borderline':
        return <span className="px-2 py-1 text-xs font-medium rounded-full bg-amber-100 text-amber-700">{t('glaucomaCenter.suspect')}</span>;
      case 'uncontrolled':
        return <span className="px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-700">{t('glaucomaCenter.uncontrolled')}</span>;
      default:
        return null;
    }
  };

  const filteredRecords = records.filter(record => {
    const matchesSearch = record.patientId?.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
                         record.patientId?.patientId?.toLowerCase().includes(searchQuery.toLowerCase());
    
    if (filterStatus === 'all') return matchesSearch;
    
    const latestIOP = getLatestIOP(record);
    if (!latestIOP) return false;
    
    const odStatus = getIOPStatus(latestIOP.OD, record.targetIOP?.OD || 21);
    const osStatus = getIOPStatus(latestIOP.OS, record.targetIOP?.OS || 21);
    
    if (filterStatus === 'uncontrolled') {
      return matchesSearch && (odStatus === 'uncontrolled' || osStatus === 'uncontrolled');
    }
    if (filterStatus === 'controlled') {
      return matchesSearch && odStatus === 'controlled' && osStatus === 'controlled';
    }
    return matchesSearch;
  });

  const stats = {
    total: records.length,
    controlled: records.filter(r => {
      const iop = getLatestIOP(r);
      if (!iop) return false;
      return iop.OD <= (r.targetIOP?.OD || 21) && iop.OS <= (r.targetIOP?.OS || 21);
    }).length,
    uncontrolled: records.filter(r => {
      const iop = getLatestIOP(r);
      if (!iop) return false;
      return iop.OD > (r.targetIOP?.OD || 21) + 3 || iop.OS > (r.targetIOP?.OS || 21) + 3;
    }).length
  };

  return (
    <SidebarLayout title={t('glaucomaCenter.sections.iopHistory')} description={t('glaucomaCenter.description')}>
      <div className="space-y-6">
        {/* Header */}
        <div className="flex items-center justify-between">
          <Link href="/glaucoma" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900">
            <ArrowLeft className="h-4 w-4" />
            {t('glaucomaCenter.title')}
          </Link>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">{t('glaucomaCenter.totalPatients')}</p>
                <p className="text-3xl font-bold text-gray-900">{stats.total}</p>
              </div>
              <Activity className="h-10 w-10 text-blue-600" />
            </div>
          </div>
          <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">{t('glaucomaCenter.iopControlled')}</p>
                <p className="text-3xl font-bold text-green-600">{stats.controlled}</p>
              </div>
              <TrendingDown className="h-10 w-10 text-green-600" />
            </div>
          </div>
          <div className="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">{t('glaucomaCenter.iopUncontrolled')}</p>
                <p className="text-3xl font-bold text-red-600">{stats.uncontrolled}</p>
              </div>
              <TrendingUp className="h-10 w-10 text-red-600" />
            </div>
          </div>
        </div>

        {/* Filters */}
        <div className="flex flex-col sm:flex-row gap-4">
          <div className="relative flex-1">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder={t('glaucomaCenter.searchPlaceholder')}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
            />
          </div>
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value)}
            className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
          >
            <option value="all">{t('glaucomaCenter.allRecords')}</option>
            <option value="controlled">{t('glaucomaCenter.controlled')}</option>
            <option value="uncontrolled">{t('glaucomaCenter.uncontrolled')}</option>
          </select>
        </div>

        {/* IOP Records Table */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('glaucomaCenter.tableHeaders.patient')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('common.type')}</th>
                  <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">{t('glaucomaCenter.tableHeaders.iopOD')}</th>
                  <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">{t('glaucomaCenter.fields.targetIop')} OD</th>
                  <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">{t('glaucomaCenter.tableHeaders.iopOS')}</th>
                  <th className="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">{t('glaucomaCenter.fields.targetIop')} OS</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('glaucomaCenter.tableHeaders.status')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('glaucomaCenter.tableHeaders.date')}</th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('glaucomaCenter.tableHeaders.actions')}</th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {isLoading ? (
                  Array.from({ length: 5 }).map((_, i) => (
                    <tr key={i} className="animate-pulse">
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-32"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-12 mx-auto"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-12 mx-auto"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-12 mx-auto"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-12 mx-auto"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-20"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-20"></div></td>
                      <td className="px-6 py-4"><div className="h-4 bg-gray-200 rounded w-16"></div></td>
                    </tr>
                  ))
                ) : filteredRecords.length === 0 ? (
                  <tr>
                    <td colSpan={9} className="px-6 py-12 text-center text-gray-500">
                      <Eye className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                      <p>{t('glaucomaCenter.noResults')}</p>
                    </td>
                  </tr>
                ) : (
                  filteredRecords.map((record) => {
                    const latestIOP = getLatestIOP(record);
                    const odStatus = latestIOP ? getIOPStatus(latestIOP.OD, record.targetIOP?.OD || 21) : 'unknown';
                    const osStatus = latestIOP ? getIOPStatus(latestIOP.OS, record.targetIOP?.OS || 21) : 'unknown';
                    const overallStatus = odStatus === 'uncontrolled' || osStatus === 'uncontrolled' 
                      ? 'uncontrolled' 
                      : odStatus === 'borderline' || osStatus === 'borderline' 
                        ? 'borderline' 
                        : 'controlled';

                    return (
                      <tr key={record._id} className="hover:bg-gray-50">
                        <td className="px-6 py-4">
                          <div>
                            <p className="font-medium text-gray-900">{record.patientId?.name}</p>
                            <p className="text-sm text-gray-500">{record.patientId?.patientId}</p>
                          </div>
                        </td>
                        <td className="px-6 py-4 text-sm text-gray-600 uppercase">{record.glaucomaType}</td>
                        <td className="px-6 py-4 text-center">
                          <span className={`text-lg font-bold ${
                            odStatus === 'controlled' ? 'text-green-600' :
                            odStatus === 'borderline' ? 'text-amber-600' : 'text-red-600'
                          }`}>
                            {latestIOP?.OD || '-'}
                          </span>
                        </td>
                        <td className="px-6 py-4 text-center text-sm text-gray-500">
                          ≤{record.targetIOP?.OD || 21}
                        </td>
                        <td className="px-6 py-4 text-center">
                          <span className={`text-lg font-bold ${
                            osStatus === 'controlled' ? 'text-green-600' :
                            osStatus === 'borderline' ? 'text-amber-600' : 'text-red-600'
                          }`}>
                            {latestIOP?.OS || '-'}
                          </span>
                        </td>
                        <td className="px-6 py-4 text-center text-sm text-gray-500">
                          ≤{record.targetIOP?.OS || 21}
                        </td>
                        <td className="px-6 py-4">{getStatusBadge(overallStatus)}</td>
                        <td className="px-6 py-4 text-sm text-gray-500">
                          {latestIOP ? new Date(latestIOP.date).toLocaleDateString() : '-'}
                        </td>
                        <td className="px-6 py-4">
                          <Link
                            href={`/glaucoma/${record._id}`}
                            className="text-blue-600 hover:text-blue-700 text-sm font-medium"
                          >
                            {t('glaucomaCenter.viewRecord')}
                          </Link>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </SidebarLayout>
  );
}
