'use client';

import { useState, useEffect, use } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import SidebarLayout from '../../../components/sidebar-layout';
import { 
  ArrowLeft, 
  Camera, 
  User, 
  Calendar,
  Eye,
  Trash2,
  XCircle
} from 'lucide-react';

interface FundusPhoto {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    phone?: string;
  };
  capturedBy?: {
    _id: string;
    name: string;
  };
  captureDate: string;
  device?: string;
  type: string;
  field?: string;
  dilation?: {
    dilated?: boolean;
    agent?: string;
  };
  OD?: {
    captured: boolean;
    imageUrl?: string;
    quality?: string;
    findings?: {
      opticDisc?: string;
      macula?: string;
      vessels?: string;
      periphery?: string;
      other?: string;
    };
  };
  OS?: {
    captured: boolean;
    imageUrl?: string;
    quality?: string;
    findings?: {
      opticDisc?: string;
      macula?: string;
      vessels?: string;
      periphery?: string;
      other?: string;
    };
  };
  interpretation?: string;
  notes?: string;
  createdAt: string;
}

export default function FundusPhotoDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [photo, setPhoto] = useState<FundusPhoto | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    fetchPhoto();
  }, [id]);

  const fetchPhoto = async () => {
    try {
      const response = await fetch(`/api/imaging/fundus/${id}`);
      if (response.ok) {
        const data = await response.json();
        setPhoto(data);
      } else {
        setError('Fundus photo not found');
      }
    } catch (err) {
      console.error('Error fetching photo:', err);
      setError('Failed to load fundus photo');
    } finally {
      setLoading(false);
    }
  };

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

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      color: 'Color Fundus',
      redFree: 'Red Free',
      autofluorescence: 'Autofluorescence (FAF)',
      icg: 'ICG Angiography',
      fa: 'Fluorescein Angiography',
      widefield: 'Widefield'
    };
    return labels[type] || type;
  };

  const renderEyeData = (eyeData: FundusPhoto['OD'], eyeLabel: string) => {
    if (!eyeData?.captured) {
      return (
        <div className="p-4 bg-gray-50 rounded-lg text-center text-gray-500">
          Not captured
        </div>
      );
    }

    return (
      <div className="space-y-4">
        {eyeData.quality && (
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-500">Quality:</span>
            <span className={`px-2 py-1 rounded text-xs font-medium ${
              eyeData.quality === 'excellent' ? 'bg-green-100 text-green-700' :
              eyeData.quality === 'good' ? 'bg-blue-100 text-blue-700' :
              eyeData.quality === 'acceptable' ? 'bg-yellow-100 text-yellow-700' :
              'bg-red-100 text-red-700'
            }`}>
              {eyeData.quality}
            </span>
          </div>
        )}

        {eyeData.findings && (
          <div className="bg-gray-50 rounded-lg p-4 space-y-3">
            <h4 className="font-medium text-gray-900">Findings</h4>
            {eyeData.findings.opticDisc && (
              <div>
                <span className="text-sm text-gray-500">Optic Disc:</span>
                <p className="text-gray-700">{eyeData.findings.opticDisc}</p>
              </div>
            )}
            {eyeData.findings.macula && (
              <div>
                <span className="text-sm text-gray-500">Macula:</span>
                <p className="text-gray-700">{eyeData.findings.macula}</p>
              </div>
            )}
            {eyeData.findings.vessels && (
              <div>
                <span className="text-sm text-gray-500">Vessels:</span>
                <p className="text-gray-700">{eyeData.findings.vessels}</p>
              </div>
            )}
            {eyeData.findings.periphery && (
              <div>
                <span className="text-sm text-gray-500">Periphery:</span>
                <p className="text-gray-700">{eyeData.findings.periphery}</p>
              </div>
            )}
          </div>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <SidebarLayout title="Fundus Photo Details" description="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>
    );
  }

  if (error || !photo) {
    return (
      <SidebarLayout title="Fundus Photo Details" description="Error">
        <div className="max-w-4xl mx-auto">
          <Link href="/imaging/fundus" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6">
            <ArrowLeft className="h-4 w-4" />
            Back to Fundus Photos
          </Link>
          <div className="bg-red-50 border border-red-200 rounded-lg p-6 text-center">
            <XCircle className="h-12 w-12 text-red-500 mx-auto mb-4" />
            <h2 className="text-lg font-semibold text-red-800">{error || 'Photo not found'}</h2>
          </div>
        </div>
      </SidebarLayout>
    );
  }

  return (
    <SidebarLayout title="Fundus Photo Details" description={getTypeLabel(photo.type)}>
      <div className="max-w-4xl mx-auto">
        <div className="mb-6 flex items-center justify-between">
          <Link href="/imaging/fundus" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900">
            <ArrowLeft className="h-4 w-4" />
            Back to Fundus Photos
          </Link>
          <button
            onClick={handleDelete}
            className="inline-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" />
            Delete
          </button>
        </div>

        {/* Header */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
          <div className="flex items-start justify-between mb-4">
            <div>
              <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                <Camera className="h-6 w-6 text-teal-600" />
                {getTypeLabel(photo.type)}
              </h1>
              {photo.device && <p className="text-gray-500 mt-1">Device: {photo.device}</p>}
            </div>
            {photo.dilation?.dilated && (
              <span className="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm font-medium">
                Dilated
              </span>
            )}
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
            <div className="flex items-center gap-3">
              <Calendar className="h-5 w-5 text-gray-400" />
              <div>
                <p className="text-xs text-gray-500">Capture Date</p>
                <p className="font-medium">{new Date(photo.captureDate).toLocaleDateString()}</p>
              </div>
            </div>
            <div className="flex items-center gap-3">
              <Eye className="h-5 w-5 text-gray-400" />
              <div>
                <p className="text-xs text-gray-500">Eyes Captured</p>
                <p className="font-medium">
                  {photo.OD?.captured && photo.OS?.captured ? 'OU (Both)' : 
                   photo.OD?.captured ? 'OD (Right)' : 
                   photo.OS?.captured ? 'OS (Left)' : 'None'}
                </p>
              </div>
            </div>
            {photo.field && (
              <div className="flex items-center gap-3">
                <Camera className="h-5 w-5 text-gray-400" />
                <div>
                  <p className="text-xs text-gray-500">Field</p>
                  <p className="font-medium capitalize">{photo.field}</p>
                </div>
              </div>
            )}
            {photo.capturedBy && (
              <div className="flex items-center gap-3">
                <User className="h-5 w-5 text-gray-400" />
                <div>
                  <p className="text-xs text-gray-500">Captured By</p>
                  <p className="font-medium">{photo.capturedBy.name}</p>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Patient Info */}
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
          <h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <User className="h-5 w-5 text-teal-600" />
            Patient
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
            <div>
              <p className="text-sm text-gray-500">Name</p>
              <Link href={`/patients/${photo.patientId._id}`} className="font-medium text-teal-600 hover:text-teal-700">
                {photo.patientId.name}
              </Link>
            </div>
            <div>
              <p className="text-sm text-gray-500">Patient ID</p>
              <p className="font-medium">{photo.patientId.patientId}</p>
            </div>
            {photo.patientId.phone && (
              <div>
                <p className="text-sm text-gray-500">Phone</p>
                <p className="font-medium">{photo.patientId.phone}</p>
              </div>
            )}
          </div>
        </div>

        {/* Eye Data */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-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">
              <Eye className="h-5 w-5 text-teal-600" />
              OD (Right Eye)
            </h2>
            {renderEyeData(photo.OD, 'OD')}
          </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">
              <Eye className="h-5 w-5 text-teal-600" />
              OS (Left Eye)
            </h2>
            {renderEyeData(photo.OS, 'OS')}
          </div>
        </div>

        {/* Interpretation */}
        {photo.interpretation && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">Interpretation</h2>
            <p className="text-gray-700 whitespace-pre-wrap">{photo.interpretation}</p>
          </div>
        )}

        {/* Notes */}
        {photo.notes && (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 mb-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">Notes</h2>
            <p className="text-gray-700 whitespace-pre-wrap">{photo.notes}</p>
          </div>
        )}

        {/* Metadata */}
        <div className="text-sm text-gray-500 text-center">
          <p>Created: {new Date(photo.createdAt).toLocaleString()}</p>
        </div>
      </div>
    </SidebarLayout>
  );
}
