'use client';

import { useState, useEffect, use } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import SidebarLayout from '../../components/sidebar-layout';
import ProtectedRoute from '../../protected-route';
import { useTranslations } from '../../hooks/useTranslations';
import { 
  Eye, 
  ArrowLeft, 
  User, 
  Calendar, 
  Activity,
  AlertTriangle,
  TrendingUp,
  Pill,
  FileText,
  Printer,
  Edit,
  Trash2,
  AlertCircle,
  CheckCircle
} from 'lucide-react';

interface GlaucomaRecord {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    dateOfBirth: string;
  };
  glaucomaType: string;
  severity: string;
  diagnosisDate: string;
  affectedEyes: string;
  targetIOP: { OD: number; OS: number };
  riskFactors: {
    familyHistory: boolean;
    myopia: boolean;
    diabetes: boolean;
    hypertension: boolean;
  };
  iopHistory: {
    date: string;
    OD: number;
    OS: number;
    method: string;
  }[];
  currentMedications: {
    name: string;
    dosage: string;
    frequency: string;
    eye: string;
  }[];
  progressionAnalysis: {
    overallStatus: string;
    iopControl: string;
  };
  notes: string;
  createdAt: string;
  updatedAt: string;
}

export default function GlaucomaDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { t } = useTranslations();
  const { id } = use(params);
  const router = useRouter();
  const [record, setRecord] = useState<GlaucomaRecord | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchRecord = async () => {
      try {
        const response = await fetch(`/api/glaucoma/${id}`);
        if (!response.ok) throw new Error('Failed to fetch record');
        const data = await response.json();
        setRecord(data.record);
      } catch (err) {
        setError('Failed to load glaucoma record');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchRecord();
  }, [id]);

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this glaucoma record?')) return;
    try {
      const response = await fetch(`/api/glaucoma/${id}`, { method: 'DELETE' });
      if (response.ok) {
        router.push('/glaucoma');
      }
    } catch (err) {
      console.error('Failed to delete record:', err);
    }
  };

  const getTypeLabel = (type: string) => {
    const typeKey = type === 'ohT' ? 'oht' : type;
    return t(`glaucomaCenter.types.${typeKey}`) || type;
  };

  const getSeverityColor = (severity: string) => {
    switch (severity) {
      case 'mild': return 'bg-green-100 text-green-700';
      case 'moderate': return 'bg-yellow-100 text-yellow-700';
      case 'severe': return 'bg-orange-100 text-orange-700';
      case 'endStage': return 'bg-red-100 text-red-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  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';
    }
  };

  if (isLoading) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('glaucomaCenter.viewRecord')} description={t('common.loading')}>
          <div className="flex items-center justify-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  if (error || !record) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('glaucomaCenter.viewRecord')} description={t('common.error')}>
          <div className="text-center py-12">
            <AlertCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
            <p className="text-red-600">{error || t('glaucomaCenter.noResults')}</p>
            <Link href="/glaucoma" className="text-blue-600 hover:underline mt-4 inline-block">
              {t('glaucomaCenter.title')}
            </Link>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  const latestIOP = record.iopHistory?.[0];

  return (
    <ProtectedRoute>
      <SidebarLayout 
        title={t('glaucomaCenter.viewRecord')} 
        description={`${record.patientId?.name || t('glaucomaCenter.tableHeaders.patient')}`}
      >
        <div className="max-w-5xl mx-auto space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <Link href="/glaucoma" className="flex items-center gap-2 text-gray-600 hover:text-gray-900">
              <ArrowLeft className="h-4 w-4" />
              {t('glaucomaCenter.title')}
            </Link>
            <div className="flex gap-2">
              <button
                onClick={() => window.print()}
                className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
              >
                <Printer className="h-4 w-4" />
                {t('glaucomaCenter.print')}
              </button>
              <button
                onClick={handleDelete}
                className="flex items-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
              >
                <Trash2 className="h-4 w-4" />
                {t('glaucomaCenter.delete')}
              </button>
            </div>
          </div>

          {/* Header Card */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div className="flex items-start justify-between">
              <div>
                <h1 className="text-2xl font-bold text-gray-900 mb-2">{getTypeLabel(record.glaucomaType)}</h1>
                <div className="flex items-center gap-3">
                  <span className={`px-3 py-1 rounded-full text-sm font-medium capitalize ${getSeverityColor(record.severity)}`}>
                    {t(`glaucomaCenter.severity.${record.severity}`) || record.severity}
                  </span>
                  <span className="text-gray-500">
                    {t('glaucomaCenter.affected')}: {record.affectedEyes === 'OU' ? t('glaucomaCenter.bothEyes') : record.affectedEyes}
                  </span>
                </div>
              </div>
              <div className="text-right">
                <p className="text-sm text-gray-500">{t('glaucomaCenter.diagnosed')}</p>
                <p className="font-medium">{new Date(record.diagnosisDate).toLocaleDateString()}</p>
              </div>
            </div>
          </div>

          {/* Patient Info & Status */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <User className="h-5 w-5 text-blue-600" />
                {t('glaucomaCenter.patientInformation')}
              </h2>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-500">{t('glaucomaCenter.name')}</p>
                  <p className="font-medium">{record.patientId?.name || 'N/A'}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">{t('glaucomaCenter.patientId')}</p>
                  <p className="font-medium">{record.patientId?.patientId || 'N/A'}</p>
                </div>
                <Link 
                  href={`/patients/${record.patientId?._id}`}
                  className="text-blue-600 hover:underline text-sm"
                >
                  {t('glaucomaCenter.viewPatientProfile')} →
                </Link>
              </div>
            </div>

            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <TrendingUp className="h-5 w-5 text-blue-600" />
                {t('glaucomaCenter.progressionStatus')}
              </h2>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-500">{t('glaucomaCenter.overallStatus')}</p>
                  <span className={`inline-block px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(record.progressionAnalysis?.overallStatus)}`}>
                    {record.progressionAnalysis?.overallStatus === 'stable' ? t('glaucomaCenter.stable') : 
                     record.progressionAnalysis?.overallStatus === 'suspectedProgression' ? t('glaucomaCenter.suspectedProgression') : 
                     t('glaucomaCenter.definiteProgression')}
                  </span>
                </div>
                <div>
                  <p className="text-sm text-gray-500">{t('glaucomaCenter.iopControl')}</p>
                  <p className="font-medium capitalize">
                    {record.progressionAnalysis?.iopControl?.replace(/([A-Z])/g, ' $1').trim() || 'N/A'}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* IOP Section */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <Activity className="h-5 w-5 text-blue-600" />
              {t('glaucomaCenter.intraocularPressure')}
            </h2>
            
            <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
              <div className="text-center p-4 bg-blue-50 rounded-lg">
                <p className="text-sm text-gray-500 mb-1">{t('glaucomaCenter.targetOD')}</p>
                <p className="text-2xl font-bold text-blue-700">{record.targetIOP?.OD || '-'}</p>
                <p className="text-xs text-gray-500">{t('glaucomaCenter.mmHg')}</p>
              </div>
              <div className="text-center p-4 bg-blue-50 rounded-lg">
                <p className="text-sm text-gray-500 mb-1">{t('glaucomaCenter.targetOS')}</p>
                <p className="text-2xl font-bold text-blue-700">{record.targetIOP?.OS || '-'}</p>
                <p className="text-xs text-gray-500">{t('glaucomaCenter.mmHg')}</p>
              </div>
              {latestIOP && (
                <>
                  <div className={`text-center p-4 rounded-lg ${latestIOP.OD > (record.targetIOP?.OD || 21) ? 'bg-red-50' : 'bg-green-50'}`}>
                    <p className="text-sm text-gray-500 mb-1">{t('glaucomaCenter.latestOD')}</p>
                    <p className={`text-2xl font-bold ${latestIOP.OD > (record.targetIOP?.OD || 21) ? 'text-red-700' : 'text-green-700'}`}>
                      {latestIOP.OD}
                    </p>
                    <p className="text-xs text-gray-500">{t('glaucomaCenter.mmHg')}</p>
                  </div>
                  <div className={`text-center p-4 rounded-lg ${latestIOP.OS > (record.targetIOP?.OS || 21) ? 'bg-red-50' : 'bg-green-50'}`}>
                    <p className="text-sm text-gray-500 mb-1">{t('glaucomaCenter.latestOS')}</p>
                    <p className={`text-2xl font-bold ${latestIOP.OS > (record.targetIOP?.OS || 21) ? 'text-red-700' : 'text-green-700'}`}>
                      {latestIOP.OS}
                    </p>
                    <p className="text-xs text-gray-500">{t('glaucomaCenter.mmHg')}</p>
                  </div>
                </>
              )}
            </div>

            {record.iopHistory && record.iopHistory.length > 0 && (
              <div>
                <h3 className="font-medium text-gray-700 mb-3">{t('glaucomaCenter.iopHistoryTable')}</h3>
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-200">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500">{t('glaucomaCenter.date')}</th>
                        <th className="px-4 py-2 text-center text-xs font-medium text-gray-500">{t('glaucomaCenter.od')}</th>
                        <th className="px-4 py-2 text-center text-xs font-medium text-gray-500">{t('glaucomaCenter.os')}</th>
                        <th className="px-4 py-2 text-left text-xs font-medium text-gray-500">{t('glaucomaCenter.method')}</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200">
                      {record.iopHistory.slice(0, 5).map((iop, index) => (
                        <tr key={index}>
                          <td className="px-4 py-2 text-sm">{new Date(iop.date).toLocaleDateString()}</td>
                          <td className="px-4 py-2 text-sm text-center font-medium">{iop.OD}</td>
                          <td className="px-4 py-2 text-sm text-center font-medium">{iop.OS}</td>
                          <td className="px-4 py-2 text-sm capitalize">{iop.method}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>
            )}
          </div>

          {/* Medications */}
          {record.currentMedications && record.currentMedications.length > 0 && (
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <Pill className="h-5 w-5 text-blue-600" />
                {t('glaucomaCenter.currentMedications')}
              </h2>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {record.currentMedications.map((med, index) => (
                  <div key={index} className="p-4 bg-gray-50 rounded-lg">
                    <p className="font-medium text-gray-900">{med.name}</p>
                    <p className="text-sm text-gray-600">
                      {med.dosage} • {med.frequency} • {med.eye}
                    </p>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Risk Factors */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
              <AlertTriangle className="h-5 w-5 text-blue-600" />
              {t('glaucomaCenter.riskFactors')}
            </h2>
            <div className="flex flex-wrap gap-2">
              {record.riskFactors?.familyHistory && (
                <span className="px-3 py-1 bg-orange-100 text-orange-700 rounded-full text-sm">{t('glaucomaCenter.familyHistory')}</span>
              )}
              {record.riskFactors?.myopia && (
                <span className="px-3 py-1 bg-orange-100 text-orange-700 rounded-full text-sm">{t('glaucomaCenter.highMyopia')}</span>
              )}
              {record.riskFactors?.diabetes && (
                <span className="px-3 py-1 bg-orange-100 text-orange-700 rounded-full text-sm">{t('glaucomaCenter.diabetes')}</span>
              )}
              {record.riskFactors?.hypertension && (
                <span className="px-3 py-1 bg-orange-100 text-orange-700 rounded-full text-sm">{t('glaucomaCenter.hypertension')}</span>
              )}
              {!record.riskFactors?.familyHistory && !record.riskFactors?.myopia && 
               !record.riskFactors?.diabetes && !record.riskFactors?.hypertension && (
                <span className="text-gray-500">{t('glaucomaCenter.noRiskFactors')}</span>
              )}
            </div>
          </div>

          {/* Notes */}
          {record.notes && (
            <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
                <FileText className="h-5 w-5 text-blue-600" />
                {t('glaucomaCenter.notes')}
              </h2>
              <p className="text-gray-700 whitespace-pre-wrap">{record.notes}</p>
            </div>
          )}

          {/* Timestamps */}
          <div className="text-sm text-gray-500 text-center">
            <p>{t('glaucomaCenter.created')}: {new Date(record.createdAt).toLocaleString()}</p>
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
