'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, 
  Focus, 
  User, 
  Calendar,
  Eye,
  Trash2,
  XCircle
} from 'lucide-react';

interface TopographyScan {
  _id: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    phone?: string;
  };
  performedBy?: {
    _id: string;
    name: string;
  };
  scanDate: string;
  device?: string;
  purpose?: string;
  OD?: {
    keratometry?: {
      simK1?: { value: number; axis: number };
      simK2?: { value: number };
      avgK?: number;
      astigmatism?: number;
    };
    pachymetry?: {
      thinnest?: number;
      thinnestLocation?: string;
    };
    indices?: {
      KPI?: number;
      ISV?: number;
      IVA?: number;
      IHA?: number;
      SAI?: number;
    };
    classification?: string;
  };
  OS?: {
    keratometry?: {
      simK1?: { value: number; axis: number };
      simK2?: { value: number };
      avgK?: number;
      astigmatism?: number;
    };
    pachymetry?: {
      thinnest?: number;
      thinnestLocation?: string;
    };
    indices?: {
      KPI?: number;
      ISV?: number;
      IVA?: number;
      IHA?: number;
      SAI?: number;
    };
    classification?: string;
  };
  interpretation?: string;
  notes?: string;
  createdAt: string;
}

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

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

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

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

  const getPurposeLabel = (purpose: string) => {
    const labels: Record<string, string> = {
      contactLens: 'Contact Lens Fitting',
      refractiveSurgery: 'Refractive Surgery Screening',
      keratoconus: 'Keratoconus Evaluation',
      postSurgery: 'Post-Surgery Follow-up',
      routine: 'Routine'
    };
    return labels[purpose] || purpose;
  };

  const getClassificationBadge = (classification?: string) => {
    if (!classification) return null;
    const colors: Record<string, string> = {
      normal: 'bg-green-100 text-green-700',
      suspect: 'bg-yellow-100 text-yellow-700',
      keratoconus: 'bg-red-100 text-red-700',
      post_lasik: 'bg-blue-100 text-blue-700',
      irregular: 'bg-orange-100 text-orange-700'
    };
    return (
      <span className={`px-2 py-1 rounded text-xs font-medium ${colors[classification] || 'bg-gray-100 text-gray-700'}`}>
        {classification.replace('_', ' ').toUpperCase()}
      </span>
    );
  };

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

    return (
      <div className="space-y-4">
        {eyeData.classification && (
          <div className="flex items-center gap-2">
            <span className="text-sm text-gray-500">Classification:</span>
            {getClassificationBadge(eyeData.classification)}
          </div>
        )}

        {eyeData.keratometry && (
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-medium text-gray-900 mb-3">Keratometry</h4>
            <div className="grid grid-cols-2 gap-3 text-sm">
              {eyeData.keratometry.simK1 && (
                <div>
                  <span className="text-gray-500">Sim K1:</span>
                  <p className="font-medium">{eyeData.keratometry.simK1.value?.toFixed(2)} D @ {eyeData.keratometry.simK1.axis}°</p>
                </div>
              )}
              {eyeData.keratometry.simK2 && (
                <div>
                  <span className="text-gray-500">Sim K2:</span>
                  <p className="font-medium">{eyeData.keratometry.simK2.value?.toFixed(2)} D</p>
                </div>
              )}
              {eyeData.keratometry.avgK !== undefined && (
                <div>
                  <span className="text-gray-500">Avg K:</span>
                  <p className="font-medium">{eyeData.keratometry.avgK.toFixed(2)} D</p>
                </div>
              )}
              {eyeData.keratometry.astigmatism !== undefined && (
                <div>
                  <span className="text-gray-500">Astigmatism:</span>
                  <p className="font-medium">{eyeData.keratometry.astigmatism.toFixed(2)} D</p>
                </div>
              )}
            </div>
          </div>
        )}

        {eyeData.pachymetry && (
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-medium text-gray-900 mb-3">Pachymetry</h4>
            <div className="grid grid-cols-2 gap-3 text-sm">
              {eyeData.pachymetry.thinnest !== undefined && (
                <div>
                  <span className="text-gray-500">Thinnest Point:</span>
                  <p className="font-medium">{eyeData.pachymetry.thinnest} µm</p>
                </div>
              )}
              {eyeData.pachymetry.thinnestLocation && (
                <div>
                  <span className="text-gray-500">Location:</span>
                  <p className="font-medium">{eyeData.pachymetry.thinnestLocation}</p>
                </div>
              )}
            </div>
          </div>
        )}

        {eyeData.indices && (
          <div className="bg-gray-50 rounded-lg p-4">
            <h4 className="font-medium text-gray-900 mb-3">Topographic Indices</h4>
            <div className="grid grid-cols-5 gap-2 text-sm text-center">
              {eyeData.indices.KPI !== undefined && (
                <div>
                  <p className="text-gray-500">KPI</p>
                  <p className="font-medium">{eyeData.indices.KPI.toFixed(2)}</p>
                </div>
              )}
              {eyeData.indices.ISV !== undefined && (
                <div>
                  <p className="text-gray-500">ISV</p>
                  <p className="font-medium">{eyeData.indices.ISV.toFixed(2)}</p>
                </div>
              )}
              {eyeData.indices.IVA !== undefined && (
                <div>
                  <p className="text-gray-500">IVA</p>
                  <p className="font-medium">{eyeData.indices.IVA.toFixed(2)}</p>
                </div>
              )}
              {eyeData.indices.IHA !== undefined && (
                <div>
                  <p className="text-gray-500">IHA</p>
                  <p className="font-medium">{eyeData.indices.IHA.toFixed(2)}</p>
                </div>
              )}
              {eyeData.indices.SAI !== undefined && (
                <div>
                  <p className="text-gray-500">SAI</p>
                  <p className="font-medium">{eyeData.indices.SAI.toFixed(2)}</p>
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <SidebarLayout title="Topography 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 || !scan) {
    return (
      <SidebarLayout title="Topography Details" description="Error">
        <div className="max-w-4xl mx-auto">
          <Link href="/imaging/topography" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6">
            <ArrowLeft className="h-4 w-4" />
            Back to Topography
          </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 || 'Scan not found'}</h2>
          </div>
        </div>
      </SidebarLayout>
    );
  }

  return (
    <SidebarLayout title="Topography Details" description="Corneal topography scan">
      <div className="max-w-4xl mx-auto">
        <div className="mb-6 flex items-center justify-between">
          <Link href="/imaging/topography" className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900">
            <ArrowLeft className="h-4 w-4" />
            Back to Topography
          </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">
                <Focus className="h-6 w-6 text-teal-600" />
                Corneal Topography
              </h1>
              {scan.purpose && <p className="text-gray-500 mt-1">{getPurposeLabel(scan.purpose)}</p>}
            </div>
            {scan.device && (
              <span className="px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm">
                {scan.device}
              </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">Scan Date</p>
                <p className="font-medium">{new Date(scan.scanDate).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 Scanned</p>
                <p className="font-medium">
                  {scan.OD && scan.OS ? 'OU (Both)' : 
                   scan.OD ? 'OD (Right)' : 
                   scan.OS ? 'OS (Left)' : 'None'}
                </p>
              </div>
            </div>
            {scan.performedBy && (
              <div className="flex items-center gap-3">
                <User className="h-5 w-5 text-gray-400" />
                <div>
                  <p className="text-xs text-gray-500">Performed By</p>
                  <p className="font-medium">{scan.performedBy.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/${scan.patientId._id}`} className="font-medium text-teal-600 hover:text-teal-700">
                {scan.patientId.name}
              </Link>
            </div>
            <div>
              <p className="text-sm text-gray-500">Patient ID</p>
              <p className="font-medium">{scan.patientId.patientId}</p>
            </div>
            {scan.patientId.phone && (
              <div>
                <p className="text-sm text-gray-500">Phone</p>
                <p className="font-medium">{scan.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(scan.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(scan.OS, 'OS')}
          </div>
        </div>

        {/* Interpretation */}
        {scan.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">{scan.interpretation}</p>
          </div>
        )}

        {/* Notes */}
        {scan.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">{scan.notes}</p>
          </div>
        )}

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