'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,
  FileText,
  Printer,
  Trash2,
  AlertCircle,
  Clock
} 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 };
    bloodPressure: { systolic: number; diastolic: number };
  };
  riskFactors: {
    hypertension: boolean;
    nephropathy: boolean;
    pregnancy: boolean;
  };
  screeningHistory: {
    date: string;
    OD: { drLevel: string; dme: boolean; findings: string[] };
    OS: { drLevel: string; dme: boolean; findings: string[] };
  }[];
  followUpSchedule: {
    nextScreening: string;
    frequency: string;
    reason: string;
  };
  notes: string;
  createdAt: string;
  updatedAt: string;
}

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

  useEffect(() => {
    const fetchRecord = async () => {
      try {
        const response = await fetch(`/api/dr-screening/${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 DR record');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchRecord();
  }, [id]);

  const handleDelete = async () => {
    if (!confirm(t('drScreening.confirmDelete'))) return;
    try {
      const response = await fetch(`/api/dr-screening/${id}`, { method: 'DELETE' });
      if (response.ok) {
        router.push('/dr-screening');
      }
    } catch (err) {
      console.error('Failed to delete record:', err);
    }
  };

  const getDRLevelLabel = (level: string) => {
    const labels: Record<string, string> = {
      'none': t('drScreening.grades.none'),
      'mild': t('drScreening.grades.mild'),
      'moderate': t('drScreening.grades.moderate'),
      'severe': t('drScreening.grades.severe'),
      'pdr': t('drScreening.grades.pdr')
    };
    return labels[level] || level;
  };

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

  if (isLoading) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('drScreening.title')} 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-indigo-600"></div>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  if (error || !record) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('drScreening.title')} 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('drScreening.recordNotFound')}</p>
            <Link href="/dr-screening" className="text-indigo-600 hover:underline mt-4 inline-block">
              {t('drScreening.title')}
            </Link>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  const isDueForScreening = record.followUpSchedule?.nextScreening && 
    new Date(record.followUpSchedule.nextScreening) <= new Date();

  return (
    <ProtectedRoute>
      <SidebarLayout 
        title={t('drScreening.viewScreening')} 
        description={`${record.patientId?.name || t('common.patient')}`}
      >
        <div className="max-w-5xl mx-auto space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <Link href="/dr-screening" className="flex items-center gap-2 text-gray-600 hover:text-gray-900">
              <ArrowLeft className="h-4 w-4" />
              {t('drScreening.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('drScreening.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('drScreening.delete')}
              </button>
            </div>
          </div>

          {/* Due for Screening Alert */}
          {isDueForScreening && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center gap-3">
              <AlertTriangle className="h-5 w-5 text-red-500" />
              <p className="text-red-700">{t('drScreening.dueForFollowUp')}</p>
            </div>
          )}

          {/* Patient Info & Diabetes Info */}
          <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-indigo-600" />
                {t('drScreening.patientInformation')}
              </h2>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-500">{t('drScreening.name')}</p>
                  <p className="font-medium">{record.patientId?.name || 'N/A'}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">{t('drScreening.patientId')}</p>
                  <p className="font-medium">{record.patientId?.patientId || 'N/A'}</p>
                </div>
                <Link 
                  href={`/patients/${record.patientId?._id}`}
                  className="text-indigo-600 hover:underline text-sm"
                >
                  {t('drScreening.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">
              <Activity className="h-5 w-5 text-indigo-600" />
              {t('drScreening.sections.diabetesHistory')}
            </h2>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-500">{t('drScreening.fields.diabetesType')}</p>
                  <p className="font-medium capitalize">{record.diabetesType?.replace(/(\d)/, ' $1') || 'Type 2'}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">{t('drScreening.fields.diabetesDuration')}</p>
                  <p className="font-medium">{record.diabetesDuration || 0} {t('drScreening.years')}</p>
                </div>
                {record.metabolicControl?.lastHba1c && (
                  <div>
                    <p className="text-sm text-gray-500">{t('drScreening.fields.hba1c')}</p>
                    <p className="font-medium">{record.metabolicControl.lastHba1c.value}%</p>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Current DR Status */}
          <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">
              <Eye className="h-5 w-5 text-indigo-600" />
              {t('drScreening.sections.fundusFindings')}
            </h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Right Eye */}
              <div className="p-4 bg-gray-50 rounded-lg">
                <h3 className="font-medium text-gray-900 mb-3">{t('drScreening.odRightEye')}</h3>
                <div className="space-y-2">
                  <div>
                    <p className="text-sm text-gray-500">{t('drScreening.drLevel')}</p>
                    <span className={`inline-block px-3 py-1 rounded-full text-sm font-medium ${getDRLevelColor(record.currentStatus?.OD?.drLevel)}`}>
                      {getDRLevelLabel(record.currentStatus?.OD?.drLevel)}
                    </span>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">{t('drScreening.dme')}</p>
                    <p className={`font-medium ${record.currentStatus?.OD?.dme ? 'text-red-600' : 'text-green-600'}`}>
                      {record.currentStatus?.OD?.dme ? t('drScreening.present') : t('drScreening.absent')}
                    </p>
                  </div>
                </div>
              </div>

              {/* Left Eye */}
              <div className="p-4 bg-gray-50 rounded-lg">
                <h3 className="font-medium text-gray-900 mb-3">{t('drScreening.osLeftEye')}</h3>
                <div className="space-y-2">
                  <div>
                    <p className="text-sm text-gray-500">{t('drScreening.drLevel')}</p>
                    <span className={`inline-block px-3 py-1 rounded-full text-sm font-medium ${getDRLevelColor(record.currentStatus?.OS?.drLevel)}`}>
                      {getDRLevelLabel(record.currentStatus?.OS?.drLevel)}
                    </span>
                  </div>
                  <div>
                    <p className="text-sm text-gray-500">{t('drScreening.dme')}</p>
                    <p className={`font-medium ${record.currentStatus?.OS?.dme ? 'text-red-600' : 'text-green-600'}`}>
                      {record.currentStatus?.OS?.dme ? t('drScreening.present') : t('drScreening.absent')}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Follow-up Schedule */}
          <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">
              <Clock className="h-5 w-5 text-indigo-600" />
              {t('drScreening.followUpSchedule')}
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div>
                <p className="text-sm text-gray-500">{t('drScreening.fields.nextScreeningDate')}</p>
                <p className={`font-medium ${isDueForScreening ? 'text-red-600' : ''}`}>
                  {record.followUpSchedule?.nextScreening 
                    ? new Date(record.followUpSchedule.nextScreening).toLocaleDateString()
                    : t('drScreening.notScheduled')}
                </p>
              </div>
              <div>
                <p className="text-sm text-gray-500">{t('drScreening.frequency')}</p>
                <p className="font-medium">{record.followUpSchedule?.frequency || t('drScreening.annual')}</p>
              </div>
              <div>
                <p className="text-sm text-gray-500">{t('drScreening.reason')}</p>
                <p className="font-medium">{record.followUpSchedule?.reason || t('drScreening.routineScreening')}</p>
              </div>
            </div>
          </div>

          {/* Screening History */}
          {record.screeningHistory && record.screeningHistory.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">
                <TrendingUp className="h-5 w-5 text-indigo-600" />
                {t('drScreening.screeningHistory')}
              </h2>
              <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('drScreening.tableHeaders.date')}</th>
                      <th className="px-4 py-2 text-center text-xs font-medium text-gray-500">{t('drScreening.odLevel')}</th>
                      <th className="px-4 py-2 text-center text-xs font-medium text-gray-500">{t('drScreening.odDme')}</th>
                      <th className="px-4 py-2 text-center text-xs font-medium text-gray-500">{t('drScreening.osLevel')}</th>
                      <th className="px-4 py-2 text-center text-xs font-medium text-gray-500">{t('drScreening.osDme')}</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {record.screeningHistory.map((screening, index) => (
                      <tr key={index}>
                        <td className="px-4 py-2 text-sm">{new Date(screening.date).toLocaleDateString()}</td>
                        <td className="px-4 py-2 text-center">
                          <span className={`inline-block px-2 py-0.5 rounded text-xs ${getDRLevelColor(screening.OD?.drLevel)}`}>
                            {getDRLevelLabel(screening.OD?.drLevel)}
                          </span>
                        </td>
                        <td className="px-4 py-2 text-center text-sm">
                          {screening.OD?.dme ? '✓' : '-'}
                        </td>
                        <td className="px-4 py-2 text-center">
                          <span className={`inline-block px-2 py-0.5 rounded text-xs ${getDRLevelColor(screening.OS?.drLevel)}`}>
                            {getDRLevelLabel(screening.OS?.drLevel)}
                          </span>
                        </td>
                        <td className="px-4 py-2 text-center text-sm">
                          {screening.OS?.dme ? '✓' : '-'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </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-indigo-600" />
                {t('drScreening.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('drScreening.created')}: {new Date(record.createdAt).toLocaleString()}</p>
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
