'use client';

import { useState, useEffect, use } from 'react';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import Link from 'next/link';
import SidebarLayout from '../../../components/sidebar-layout';
import ProtectedRoute from '../../../protected-route';
import { useTranslations } from '@/app/hooks/useTranslations';
import toast from 'react-hot-toast';
import { 
  Eye, 
  Save, 
  ArrowLeft,
  User,
  Activity,
  Glasses,
  Target,
  FileText,
  Plus,
  X,
  AlertCircle
} from 'lucide-react';

interface Patient {
  _id: string;
  name: string;
  patientId: string;
  email: string;
  phone: string;
  dateOfBirth?: string;
}

export default function EditEyeExamPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const { data: session } = useSession();
  const { t } = useTranslations();
  const [isLoading, setIsLoading] = useState(false);
  const [isFetching, setIsFetching] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
  const [activeTab, setActiveTab] = useState('basic');
  const [errors, setErrors] = useState<Record<string, string>>({});

  const [formData, setFormData] = useState({
    chiefComplaint: '',
    historyOfPresentIllness: '',
    visualAcuity: {
      uncorrected: {
        distance: { OD: '', OS: '' },
        near: { OD: '', OS: '' }
      },
      corrected: {
        distance: { OD: '', OS: '' },
        near: { OD: '', OS: '' }
      },
      pinhole: { OD: '', OS: '' },
      method: 'snellen'
    },
    refraction: {
      autoRefraction: {
        OD: { sphere: '', cylinder: '', axis: '' },
        OS: { sphere: '', cylinder: '', axis: '' },
        pupilDistance: ''
      },
      subjectiveRefraction: {
        OD: { sphere: '', cylinder: '', axis: '', add: '' },
        OS: { sphere: '', cylinder: '', axis: '', add: '' },
        pupilDistance: ''
      }
    },
    iop: {
      OD: '',
      OS: '',
      method: 'goldmann',
      time: new Date().toISOString()
    },
    slitLampExam: {
      lids: { OD: 'Normal', OS: 'Normal' },
      conjunctiva: { OD: 'Normal', OS: 'Normal' },
      cornea: { OD: 'Clear', OS: 'Clear' },
      anteriorChamber: { OD: 'Deep & Quiet', OS: 'Deep & Quiet' },
      iris: { OD: 'Normal', OS: 'Normal' },
      pupil: { OD: 'Round, reactive', OS: 'Round, reactive', rapd: 'none' },
      lens: { OD: 'Clear', OS: 'Clear' }
    },
    fundusExam: {
      method: 'indirect',
      dilation: { dilated: false, agent: '' },
      opticDisc: {
        OD: { cdRatio: '', color: 'Pink', margins: 'Sharp' },
        OS: { cdRatio: '', color: 'Pink', margins: 'Sharp' }
      },
      macula: { OD: 'Normal foveal reflex', OS: 'Normal foveal reflex' },
      vessels: { OD: 'Normal AV ratio', OS: 'Normal AV ratio' },
      periphery: { OD: 'Flat, no holes/tears', OS: 'Flat, no holes/tears' }
    },
    pupilExam: {
      OD: { size: '3', shape: 'Round', reaction: 'Brisk' },
      OS: { size: '3', shape: 'Round', reaction: 'Brisk' },
      rapd: 'none'
    },
    diagnosis: [{ icdCode: '', description: '', eye: 'OU', severity: '' }],
    plan: '',
    medications: [] as { name: string; dosage: string; frequency: string; duration: string; eye: string }[],
    followUp: { recommended: true, interval: '1 month', reason: '' },
    notes: ''
  });

  useEffect(() => {
    const fetchExamination = async () => {
      try {
        const response = await fetch(`/api/eye-exam/${id}`);
        if (!response.ok) {
          throw new Error('Failed to fetch examination');
        }
        const data = await response.json();
        const exam = data.examination;
        
        if (exam.patientId) {
          setSelectedPatient({
            _id: exam.patientId._id,
            name: exam.patientId.name,
            patientId: exam.patientId.patientId,
            email: exam.patientId.email,
            phone: exam.patientId.phone,
            dateOfBirth: exam.patientId.dateOfBirth
          });
        }
        
        setFormData({
          chiefComplaint: exam.chiefComplaint || '',
          historyOfPresentIllness: exam.historyOfPresentIllness || '',
          visualAcuity: exam.visualAcuity || formData.visualAcuity,
          refraction: exam.refraction || formData.refraction,
          iop: {
            OD: exam.iop?.OD?.toString() || '',
            OS: exam.iop?.OS?.toString() || '',
            method: exam.iop?.method || 'goldmann',
            time: exam.iop?.time || new Date().toISOString()
          },
          slitLampExam: exam.slitLampExam || formData.slitLampExam,
          fundusExam: exam.fundusExam || formData.fundusExam,
          pupilExam: exam.pupilExam || formData.pupilExam,
          diagnosis: exam.diagnosis?.length > 0 ? exam.diagnosis : [{ icdCode: '', description: '', eye: 'OU', severity: '' }],
          plan: exam.plan || '',
          medications: exam.medications || [],
          followUp: exam.followUp || { recommended: true, interval: '1 month', reason: '' },
          notes: exam.notes || ''
        });
      } catch (err) {
        setError(t('eyeExam.editPage.failedToLoad'));
        console.error(err);
      } finally {
        setIsFetching(false);
      }
    };

    fetchExamination();
  }, [id, t]);

  const validateForm = (): { valid: boolean; errors: Record<string, string>; errorTab?: string } => {
    const newErrors: Record<string, string> = {};
    let errorTab: string | undefined;
    
    if (!formData.chiefComplaint || formData.chiefComplaint.trim() === '') {
      newErrors.chiefComplaint = 'Chief complaint is required';
      if (!errorTab) errorTab = 'basic';
    }
    
    return {
      valid: Object.keys(newErrors).length === 0,
      errors: newErrors,
      errorTab
    };
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const validation = validateForm();
    
    if (!validation.valid) {
      setErrors(validation.errors);
      
      if (validation.errorTab && activeTab !== validation.errorTab) {
        setActiveTab(validation.errorTab);
      }
      
      const errorMessages = Object.values(validation.errors).join(', ');
      toast.error(errorMessages || 'Please fill in all required fields');
      return;
    }
    
    setErrors({});
    setIsLoading(true);

    try {
      const response = await fetch(`/api/eye-exam/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      });

      const data = await response.json();
      
      if (!response.ok) {
        toast.error(data.error || t('eyeExam.editPage.updateFailed'));
        return;
      }

      toast.success(t('eyeExam.editPage.updateSuccess'));
      router.push(`/eye-exam/${id}`);
    } catch (error) {
      console.error('Error updating examination:', error);
      toast.error(t('eyeExam.editPage.updateFailed'));
    } finally {
      setIsLoading(false);
    }
  };

  const addMedication = () => {
    setFormData(prev => ({
      ...prev,
      medications: [...prev.medications, { name: '', dosage: '', frequency: '', duration: '', eye: 'OU' }]
    }));
  };

  const removeMedication = (index: number) => {
    setFormData(prev => ({
      ...prev,
      medications: prev.medications.filter((_, i) => i !== index)
    }));
  };

  const updateMedication = (index: number, field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      medications: prev.medications.map((med, i) => 
        i === index ? { ...med, [field]: value } : med
      )
    }));
  };

  const tabs = [
    { id: 'basic', label: t('eyeExam.tabs.basicInfo'), icon: FileText },
    { id: 'va', label: t('eyeExam.tabs.visualAcuity'), icon: Eye },
    { id: 'refraction', label: t('eyeExam.tabs.refraction'), icon: Glasses },
    { id: 'iop', label: t('eyeExam.tabs.iop'), icon: Activity },
    { id: 'anterior', label: t('eyeExam.tabs.anteriorSegment'), icon: Target },
    { id: 'fundus', label: t('eyeExam.tabs.fundus'), icon: Eye },
    { id: 'diagnosis', label: t('eyeExam.tabs.assessment'), icon: FileText }
  ];

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

  if (error) {
    return (
      <ProtectedRoute>
        <SidebarLayout title={t('eyeExam.editPage.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}</p>
            <Link href="/eye-exam" className="text-teal-600 hover:underline mt-4 inline-block">
              {t('eyeExam.backToExaminations')}
            </Link>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  return (
    <ProtectedRoute>
      <SidebarLayout title={t('eyeExam.editPage.title')} description={t('eyeExam.editPage.description')}>
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Patient Information (Read-only) */}
          <div className="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
            <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
              <User className="h-5 w-5 text-blue-600" />
              {t('common.patientInformation')}
            </h3>
            
            {selectedPatient && (
              <div className="flex items-center justify-between p-4 bg-blue-50 rounded-lg">
                <div>
                  <p className="font-semibold text-gray-900">{selectedPatient.name}</p>
                  <p className="text-sm text-gray-600">
                    ID: {selectedPatient.patientId} 
                    {selectedPatient.dateOfBirth && ` | DOB: ${new Date(selectedPatient.dateOfBirth).toLocaleDateString()}`}
                  </p>
                </div>
                <Link 
                  href={`/patients/${selectedPatient._id}`}
                  className="text-teal-600 hover:text-teal-700 text-sm"
                >
                  {t('common.viewProfile')} →
                </Link>
              </div>
            )}
          </div>

          {/* Tab Navigation */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="flex overflow-x-auto border-b">
              {tabs.map(tab => (
                <button
                  key={tab.id}
                  type="button"
                  onClick={() => setActiveTab(tab.id)}
                  className={`flex items-center gap-2 px-6 py-4 text-sm font-medium whitespace-nowrap transition-colors ${
                    activeTab === tab.id
                      ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50/50'
                      : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
                  }`}
                >
                  <tab.icon className="h-4 w-4" />
                  {tab.label}
                </button>
              ))}
            </div>

            <div className="p-6">
              {/* Basic Info Tab */}
              {activeTab === 'basic' && (
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      {t('eyeExam.chiefComplaint')} <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="text"
                      value={formData.chiefComplaint}
                      onChange={(e) => {
                        setFormData(prev => ({ ...prev, chiefComplaint: e.target.value }));
                        if (errors.chiefComplaint) {
                          setErrors(prev => ({ ...prev, chiefComplaint: '' }));
                        }
                      }}
                      className={`w-full px-4 py-2.5 border rounded-lg focus:ring-2 focus:ring-blue-500 ${
                        errors.chiefComplaint ? 'border-red-300 bg-red-50' : 'border-gray-200'
                      }`}
                      placeholder={t('eyeExam.chiefComplaintPlaceholder')}
                    />
                    {errors.chiefComplaint && (
                      <p className="text-red-500 text-sm mt-1">{errors.chiefComplaint}</p>
                    )}
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      {t('eyeExam.historyOfPresentIllness')}
                    </label>
                    <textarea
                      value={formData.historyOfPresentIllness}
                      onChange={(e) => setFormData(prev => ({ ...prev, historyOfPresentIllness: e.target.value }))}
                      className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500"
                      rows={4}
                      placeholder={t('eyeExam.detailedHistoryPlaceholder')}
                    />
                  </div>
                </div>
              )}

              {/* Visual Acuity Tab */}
              {activeTab === 'va' && (
                <div className="space-y-6">
                  <div className="flex gap-4 mb-4">
                    <label className="flex items-center gap-2">
                      <input
                        type="radio"
                        checked={formData.visualAcuity.method === 'snellen'}
                        onChange={() => setFormData(prev => ({ 
                          ...prev, 
                          visualAcuity: { ...prev.visualAcuity, method: 'snellen' } 
                        }))}
                        className="text-blue-600"
                      />
                      Snellen
                    </label>
                    <label className="flex items-center gap-2">
                      <input
                        type="radio"
                        checked={formData.visualAcuity.method === 'logmar'}
                        onChange={() => setFormData(prev => ({ 
                          ...prev, 
                          visualAcuity: { ...prev.visualAcuity, method: 'logmar' } 
                        }))}
                        className="text-blue-600"
                      />
                      LogMAR
                    </label>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    {/* Uncorrected VA */}
                    <div className="bg-gray-50 p-4 rounded-lg">
                      <h4 className="font-medium text-gray-900 mb-4">{t('eyeExam.uncorrectedVA')}</h4>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.distanceOD')}</label>
                          <input
                            type="text"
                            value={formData.visualAcuity.uncorrected.distance.OD}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              visualAcuity: {
                                ...prev.visualAcuity,
                                uncorrected: {
                                  ...prev.visualAcuity.uncorrected,
                                  distance: { ...prev.visualAcuity.uncorrected.distance, OD: e.target.value }
                                }
                              }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="20/20"
                          />
                        </div>
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.distanceOS')}</label>
                          <input
                            type="text"
                            value={formData.visualAcuity.uncorrected.distance.OS}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              visualAcuity: {
                                ...prev.visualAcuity,
                                uncorrected: {
                                  ...prev.visualAcuity.uncorrected,
                                  distance: { ...prev.visualAcuity.uncorrected.distance, OS: e.target.value }
                                }
                              }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="20/20"
                          />
                        </div>
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.nearOD')}</label>
                          <input
                            type="text"
                            value={formData.visualAcuity.uncorrected.near.OD}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              visualAcuity: {
                                ...prev.visualAcuity,
                                uncorrected: {
                                  ...prev.visualAcuity.uncorrected,
                                  near: { ...prev.visualAcuity.uncorrected.near, OD: e.target.value }
                                }
                              }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="J1"
                          />
                        </div>
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.nearOS')}</label>
                          <input
                            type="text"
                            value={formData.visualAcuity.uncorrected.near.OS}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              visualAcuity: {
                                ...prev.visualAcuity,
                                uncorrected: {
                                  ...prev.visualAcuity.uncorrected,
                                  near: { ...prev.visualAcuity.uncorrected.near, OS: e.target.value }
                                }
                              }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="J1"
                          />
                        </div>
                      </div>
                    </div>

                    {/* Corrected VA */}
                    <div className="bg-blue-50 p-4 rounded-lg">
                      <h4 className="font-medium text-gray-900 mb-4">{t('eyeExam.correctedVA')}</h4>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.distanceOD')}</label>
                          <input
                            type="text"
                            value={formData.visualAcuity.corrected.distance.OD}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              visualAcuity: {
                                ...prev.visualAcuity,
                                corrected: {
                                  ...prev.visualAcuity.corrected,
                                  distance: { ...prev.visualAcuity.corrected.distance, OD: e.target.value }
                                }
                              }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="20/20"
                          />
                        </div>
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.distanceOS')}</label>
                          <input
                            type="text"
                            value={formData.visualAcuity.corrected.distance.OS}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              visualAcuity: {
                                ...prev.visualAcuity,
                                corrected: {
                                  ...prev.visualAcuity.corrected,
                                  distance: { ...prev.visualAcuity.corrected.distance, OS: e.target.value }
                                }
                              }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="20/20"
                          />
                        </div>
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.nearOD')}</label>
                          <input
                            type="text"
                            value={formData.visualAcuity.corrected.near.OD}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              visualAcuity: {
                                ...prev.visualAcuity,
                                corrected: {
                                  ...prev.visualAcuity.corrected,
                                  near: { ...prev.visualAcuity.corrected.near, OD: e.target.value }
                                }
                              }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="J1"
                          />
                        </div>
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.nearOS')}</label>
                          <input
                            type="text"
                            value={formData.visualAcuity.corrected.near.OS}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              visualAcuity: {
                                ...prev.visualAcuity,
                                corrected: {
                                  ...prev.visualAcuity.corrected,
                                  near: { ...prev.visualAcuity.corrected.near, OS: e.target.value }
                                }
                              }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="J1"
                          />
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Pinhole */}
                  <div className="bg-amber-50 p-4 rounded-lg">
                    <h4 className="font-medium text-gray-900 mb-4">{t('eyeExam.pinholeVA')}</h4>
                    <div className="grid grid-cols-2 gap-4 max-w-md">
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">OD</label>
                        <input
                          type="text"
                          value={formData.visualAcuity.pinhole.OD}
                          onChange={(e) => setFormData(prev => ({
                            ...prev,
                            visualAcuity: {
                              ...prev.visualAcuity,
                              pinhole: { ...prev.visualAcuity.pinhole, OD: e.target.value }
                            }
                          }))}
                          className="w-full px-3 py-2 border rounded-lg"
                          placeholder="20/20"
                        />
                      </div>
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">OS</label>
                        <input
                          type="text"
                          value={formData.visualAcuity.pinhole.OS}
                          onChange={(e) => setFormData(prev => ({
                            ...prev,
                            visualAcuity: {
                              ...prev.visualAcuity,
                              pinhole: { ...prev.visualAcuity.pinhole, OS: e.target.value }
                            }
                          }))}
                          className="w-full px-3 py-2 border rounded-lg"
                          placeholder="20/20"
                        />
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* IOP Tab */}
              {activeTab === 'iop' && (
                <div className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">OD (mmHg)</label>
                      <input
                        type="number"
                        value={formData.iop.OD}
                        onChange={(e) => setFormData(prev => ({
                          ...prev,
                          iop: { ...prev.iop, OD: e.target.value }
                        }))}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500"
                        placeholder="e.g., 16"
                        min="0"
                        max="70"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">OS (mmHg)</label>
                      <input
                        type="number"
                        value={formData.iop.OS}
                        onChange={(e) => setFormData(prev => ({
                          ...prev,
                          iop: { ...prev.iop, OS: e.target.value }
                        }))}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500"
                        placeholder="e.g., 16"
                        min="0"
                        max="70"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">{t('eyeExam.method')}</label>
                      <select
                        value={formData.iop.method}
                        onChange={(e) => setFormData(prev => ({
                          ...prev,
                          iop: { ...prev.iop, method: e.target.value }
                        }))}
                        className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500"
                      >
                        <option value="goldmann">Goldmann Applanation</option>
                        <option value="tonopen">Tonopen</option>
                        <option value="icare">iCare Rebound</option>
                        <option value="ncT">Non-Contact (Air Puff)</option>
                        <option value="palpation">Digital Palpation</option>
                      </select>
                    </div>
                  </div>
                  
                  {(Number(formData.iop.OD) > 21 || Number(formData.iop.OS) > 21) && (
                    <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                      <p className="text-red-800 font-medium">
                        {t('eyeExam.elevatedIOPWarning')}
                      </p>
                    </div>
                  )}
                </div>
              )}

              {/* Diagnosis Tab */}
              {activeTab === 'diagnosis' && (
                <div className="space-y-6">
                  <div>
                    <div className="flex items-center justify-between mb-4">
                      <label className="block text-sm font-medium text-gray-700">{t('eyeExam.diagnosis')}</label>
                      <button
                        type="button"
                        onClick={() => setFormData(prev => ({
                          ...prev,
                          diagnosis: [...prev.diagnosis, { icdCode: '', description: '', eye: 'OU', severity: '' }]
                        }))}
                        className="text-blue-600 hover:text-blue-700 text-sm flex items-center gap-1"
                      >
                        <Plus className="h-4 w-4" /> {t('eyeExam.addDiagnosis')}
                      </button>
                    </div>
                    
                    {formData.diagnosis.map((diag, index) => (
                      <div key={index} className="grid grid-cols-4 gap-4 mb-4 p-4 bg-gray-50 rounded-lg">
                        <div>
                          <label className="block text-xs text-gray-500 mb-1">{t('eyeExam.icdCode')}</label>
                          <input
                            type="text"
                            value={diag.icdCode}
                            onChange={(e) => {
                              const newDiagnosis = [...formData.diagnosis];
                              newDiagnosis[index].icdCode = e.target.value;
                              setFormData(prev => ({ ...prev, diagnosis: newDiagnosis }));
                            }}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="H40.10"
                          />
                        </div>
                        <div className="col-span-2">
                          <label className="block text-xs text-gray-500 mb-1">{t('eyeExam.description')}</label>
                          <input
                            type="text"
                            value={diag.description}
                            onChange={(e) => {
                              const newDiagnosis = [...formData.diagnosis];
                              newDiagnosis[index].description = e.target.value;
                              setFormData(prev => ({ ...prev, diagnosis: newDiagnosis }));
                            }}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="Primary open-angle glaucoma"
                          />
                        </div>
                        <div>
                          <label className="block text-xs text-gray-500 mb-1">{t('eyeExam.eye')}</label>
                          <select
                            value={diag.eye}
                            onChange={(e) => {
                              const newDiagnosis = [...formData.diagnosis];
                              newDiagnosis[index].eye = e.target.value;
                              setFormData(prev => ({ ...prev, diagnosis: newDiagnosis }));
                            }}
                            className="w-full px-3 py-2 border rounded-lg"
                          >
                            <option value="OD">OD ({t('common.right')})</option>
                            <option value="OS">OS ({t('common.left')})</option>
                            <option value="OU">OU ({t('common.both')})</option>
                          </select>
                        </div>
                      </div>
                    ))}
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">{t('eyeExam.plan')}</label>
                    <textarea
                      value={formData.plan}
                      onChange={(e) => setFormData(prev => ({ ...prev, plan: e.target.value }))}
                      className="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500"
                      rows={4}
                      placeholder={t('eyeExam.planPlaceholder')}
                    />
                  </div>

                  {/* Medications */}
                  <div>
                    <div className="flex items-center justify-between mb-4">
                      <label className="block text-sm font-medium text-gray-700">{t('eyeExam.medications')}</label>
                      <button
                        type="button"
                        onClick={addMedication}
                        className="text-blue-600 hover:text-blue-700 text-sm flex items-center gap-1"
                      >
                        <Plus className="h-4 w-4" /> {t('eyeExam.addMedication')}
                      </button>
                    </div>
                    
                    {formData.medications.map((med, index) => (
                      <div key={index} className="grid grid-cols-6 gap-3 mb-3 p-3 bg-gray-50 rounded-lg items-end">
                        <div>
                          <label className="block text-xs text-gray-500 mb-1">{t('eyeExam.medication')}</label>
                          <input
                            type="text"
                            value={med.name}
                            onChange={(e) => updateMedication(index, 'name', e.target.value)}
                            className="w-full px-3 py-2 border rounded-lg text-sm"
                            placeholder="Latanoprost"
                          />
                        </div>
                        <div>
                          <label className="block text-xs text-gray-500 mb-1">{t('eyeExam.dosage')}</label>
                          <input
                            type="text"
                            value={med.dosage}
                            onChange={(e) => updateMedication(index, 'dosage', e.target.value)}
                            className="w-full px-3 py-2 border rounded-lg text-sm"
                            placeholder="0.005%"
                          />
                        </div>
                        <div>
                          <label className="block text-xs text-gray-500 mb-1">{t('eyeExam.frequency')}</label>
                          <input
                            type="text"
                            value={med.frequency}
                            onChange={(e) => updateMedication(index, 'frequency', e.target.value)}
                            className="w-full px-3 py-2 border rounded-lg text-sm"
                            placeholder="Once daily"
                          />
                        </div>
                        <div>
                          <label className="block text-xs text-gray-500 mb-1">{t('eyeExam.duration')}</label>
                          <input
                            type="text"
                            value={med.duration}
                            onChange={(e) => updateMedication(index, 'duration', e.target.value)}
                            className="w-full px-3 py-2 border rounded-lg text-sm"
                            placeholder="3 months"
                          />
                        </div>
                        <div>
                          <label className="block text-xs text-gray-500 mb-1">{t('eyeExam.eye')}</label>
                          <select
                            value={med.eye}
                            onChange={(e) => updateMedication(index, 'eye', e.target.value)}
                            className="w-full px-3 py-2 border rounded-lg text-sm"
                          >
                            <option value="OD">OD</option>
                            <option value="OS">OS</option>
                            <option value="OU">OU</option>
                          </select>
                        </div>
                        <button
                          type="button"
                          onClick={() => removeMedication(index)}
                          className="p-2 text-red-500 hover:bg-red-50 rounded-lg"
                        >
                          <X className="h-5 w-5" />
                        </button>
                      </div>
                    ))}
                  </div>

                  {/* Follow-up */}
                  <div className="grid grid-cols-3 gap-4">
                    <div>
                      <label className="flex items-center gap-2">
                        <input
                          type="checkbox"
                          checked={formData.followUp.recommended}
                          onChange={(e) => setFormData(prev => ({
                            ...prev,
                            followUp: { ...prev.followUp, recommended: e.target.checked }
                          }))}
                          className="rounded text-blue-600"
                        />
                        <span className="text-sm font-medium text-gray-700">{t('eyeExam.followUpRecommended')}</span>
                      </label>
                    </div>
                    {formData.followUp.recommended && (
                      <>
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.interval')}</label>
                          <select
                            value={formData.followUp.interval}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              followUp: { ...prev.followUp, interval: e.target.value }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                          >
                            <option value="1 week">1 Week</option>
                            <option value="2 weeks">2 Weeks</option>
                            <option value="1 month">1 Month</option>
                            <option value="3 months">3 Months</option>
                            <option value="6 months">6 Months</option>
                            <option value="1 year">1 Year</option>
                          </select>
                        </div>
                        <div>
                          <label className="block text-sm text-gray-600 mb-1">{t('eyeExam.reason')}</label>
                          <input
                            type="text"
                            value={formData.followUp.reason}
                            onChange={(e) => setFormData(prev => ({
                              ...prev,
                              followUp: { ...prev.followUp, reason: e.target.value }
                            }))}
                            className="w-full px-3 py-2 border rounded-lg"
                            placeholder="IOP check, visual field..."
                          />
                        </div>
                      </>
                    )}
                  </div>
                </div>
              )}

              {/* Placeholder content for other tabs */}
              {activeTab === 'refraction' && (
                <div className="text-center py-8 text-gray-500">
                  <Glasses className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                  <p>{t('eyeExam.refractionDescription')}</p>
                </div>
              )}

              {activeTab === 'anterior' && (
                <div className="text-center py-8 text-gray-500">
                  <Target className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                  <p>{t('eyeExam.anteriorSegmentDescription')}</p>
                </div>
              )}

              {activeTab === 'fundus' && (
                <div className="text-center py-8 text-gray-500">
                  <Eye className="h-12 w-12 mx-auto mb-4 text-gray-300" />
                  <p>{t('eyeExam.fundusDescription')}</p>
                </div>
              )}
            </div>
          </div>

          {/* Action Buttons */}
          <div className="flex justify-between">
            <Link
              href={`/eye-exam/${id}`}
              className="flex items-center gap-2 px-6 py-3 text-gray-600 hover:text-gray-800"
            >
              <ArrowLeft className="h-5 w-5" />
              {t('common.cancel')}
            </Link>
            
            <button
              type="submit"
              disabled={isLoading}
              className="flex items-center gap-2 px-8 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium"
            >
              {isLoading ? (
                <>
                  <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                  {t('eyeExam.editPage.updating')}
                </>
              ) : (
                <>
                  <Save className="h-5 w-5" />
                  {t('eyeExam.editPage.updateExamination')}
                </>
              )}
            </button>
          </div>
        </form>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
