'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 { 
  Glasses, 
  ArrowLeft, 
  User, 
  Calendar, 
  Clock, 
  Eye,
  FileText,
  Printer,
  Edit,
  Trash2,
  AlertCircle,
  CheckCircle,
  XCircle
} from 'lucide-react';

interface Prescription {
  _id: string;
  prescriptionNumber: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    email: string;
    phone: string;
    dateOfBirth: string;
    gender: string;
  };
  doctorId: {
    name: string;
    email: string;
  };
  prescriptionDate: string;
  expiryDate: string;
  type: 'spectacles' | 'contactLens' | 'both';
  spectacles?: {
    OD: {
      sphere: number;
      cylinder: number;
      axis: number;
      add: number;
      prism: number;
      prismBase: string;
      pd: number;
    };
    OS: {
      sphere: number;
      cylinder: number;
      axis: number;
      add: number;
      prism: number;
      prismBase: string;
      pd: number;
    };
    lensType: string;
    lensCoatings: string[];
    lensMaterial: string;
    tint: string;
    photochromic: boolean;
    frameRecommendations: string;
  };
  contactLens?: {
    OD: {
      baseCurve: number;
      diameter: number;
      power: number;
      cylinder: number;
      axis: number;
      brand: string;
      modality: string;
    };
    OS: {
      baseCurve: number;
      diameter: number;
      power: number;
      cylinder: number;
      axis: number;
      brand: string;
      modality: string;
    };
  };
  status: 'issued' | 'filled' | 'expired' | 'cancelled';
  notes: string;
  createdAt: string;
  updatedAt: string;
}

export default function PrescriptionDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params);
  const router = useRouter();
  const [prescription, setPrescription] = useState<Prescription | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchPrescription = async () => {
      try {
        const response = await fetch(`/api/prescriptions/${id}`);
        if (!response.ok) {
          throw new Error('Failed to fetch prescription');
        }
        const data = await response.json();
        setPrescription(data.prescription);
      } catch (err) {
        setError('Failed to load prescription details');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPrescription();
  }, [id]);

  const handleDelete = async () => {
    if (!confirm('Are you sure you want to delete this prescription?')) return;

    try {
      const response = await fetch(`/api/prescriptions/${id}`, { method: 'DELETE' });
      if (response.ok) {
        router.push('/prescriptions');
      }
    } catch (err) {
      console.error('Failed to delete prescription:', err);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'issued': return 'bg-blue-100 text-blue-700';
      case 'filled': return 'bg-green-100 text-green-700';
      case 'expired': return 'bg-red-100 text-red-700';
      case 'cancelled': return 'bg-gray-100 text-gray-700';
      default: return 'bg-gray-100 text-gray-700';
    }
  };

  const formatValue = (val: number, showPlus = false) => {
    if (val === 0) return '0.00';
    return showPlus && val > 0 ? `+${val.toFixed(2)}` : val.toFixed(2);
  };

  const isExpired = prescription ? new Date(prescription.expiryDate) < new Date() : false;

  if (isLoading) {
    return (
      <ProtectedRoute>
        <SidebarLayout title="Optical Prescription" 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>
      </ProtectedRoute>
    );
  }

  if (error || !prescription) {
    return (
      <ProtectedRoute>
        <SidebarLayout title="Optical Prescription" description="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 || 'Prescription not found'}</p>
            <Link href="/prescriptions" className="text-teal-600 hover:underline mt-4 inline-block">
              Back to Prescriptions
            </Link>
          </div>
        </SidebarLayout>
      </ProtectedRoute>
    );
  }

  return (
    <ProtectedRoute>
      <SidebarLayout 
        title="Optical Prescription" 
        description={`Rx #${prescription.prescriptionNumber}`}
      >
        <div className="max-w-5xl mx-auto space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <Link href="/prescriptions" className="flex items-center gap-2 text-gray-600 hover:text-gray-900">
              <ArrowLeft className="h-4 w-4" />
              Back to Prescriptions
            </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" />
                Print
              </button>
              <Link
                href={`/prescriptions/${id}/edit`}
                className="flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700"
              >
                <Edit className="h-4 w-4" />
                Edit
              </Link>
              <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" />
                Delete
              </button>
            </div>
          </div>

          {/* Status Banner */}
          {isExpired && prescription.status !== 'expired' && (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center gap-3">
              <XCircle className="h-5 w-5 text-red-500" />
              <p className="text-red-700">This prescription has expired and needs to be renewed.</p>
            </div>
          )}

          {/* Prescription Header Card */}
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div className="flex items-start justify-between">
              <div>
                <div className="flex items-center gap-3 mb-2">
                  <h1 className="text-2xl font-bold text-gray-900">Rx #{prescription.prescriptionNumber}</h1>
                  <span className={`px-3 py-1 rounded-full text-sm font-medium ${getStatusColor(prescription.status)}`}>
                    {prescription.status.charAt(0).toUpperCase() + prescription.status.slice(1)}
                  </span>
                </div>
                <p className="text-gray-500">
                  {prescription.type === 'spectacles' && 'Spectacles Prescription'}
                  {prescription.type === 'contactLens' && 'Contact Lens Prescription'}
                  {prescription.type === 'both' && 'Spectacles & Contact Lens Prescription'}
                </p>
              </div>
              <div className="text-right">
                <p className="text-sm text-gray-500">Valid Until</p>
                <p className={`font-medium ${isExpired ? 'text-red-600' : 'text-gray-900'}`}>
                  {new Date(prescription.expiryDate).toLocaleDateString()}
                </p>
              </div>
            </div>
          </div>

          {/* Patient & Doctor 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-teal-600" />
                Patient Information
              </h2>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-500">Name</p>
                  <p className="font-medium">{prescription.patientId?.name || 'N/A'}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Patient ID</p>
                  <p className="font-medium">{prescription.patientId?.patientId || 'N/A'}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Date of Birth</p>
                  <p className="font-medium">
                    {prescription.patientId?.dateOfBirth 
                      ? new Date(prescription.patientId.dateOfBirth).toLocaleDateString() 
                      : 'N/A'}
                  </p>
                </div>
                <Link 
                  href={`/patients/${prescription.patientId?._id}`}
                  className="text-teal-600 hover:underline text-sm"
                >
                  View Patient Profile →
                </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">
                <Calendar className="h-5 w-5 text-teal-600" />
                Prescription Info
              </h2>
              <div className="space-y-3">
                <div>
                  <p className="text-sm text-gray-500">Prescribed Date</p>
                  <p className="font-medium">{new Date(prescription.prescriptionDate).toLocaleDateString()}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Prescriber</p>
                  <p className="font-medium">{prescription.doctorId?.name || 'N/A'}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Expiry Date</p>
                  <p className={`font-medium ${isExpired ? 'text-red-600' : ''}`}>
                    {new Date(prescription.expiryDate).toLocaleDateString()}
                    {isExpired && ' (Expired)'}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* Spectacles Prescription */}
          {(prescription.type === 'spectacles' || prescription.type === 'both') && prescription.spectacles && (
            <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">
                <Glasses className="h-5 w-5 text-teal-600" />
                Spectacles Prescription
              </h2>
              
              {/* Refraction Table */}
              <div className="overflow-x-auto mb-6">
                <table className="min-w-full">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">Eye</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Sphere</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Cylinder</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Axis</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Add</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Prism</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">PD</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    <tr>
                      <td className="px-4 py-3 font-medium text-gray-900">OD (Right)</td>
                      <td className="px-4 py-3 text-center">{formatValue(prescription.spectacles.OD.sphere, true)}</td>
                      <td className="px-4 py-3 text-center">{formatValue(prescription.spectacles.OD.cylinder)}</td>
                      <td className="px-4 py-3 text-center">{prescription.spectacles.OD.axis}°</td>
                      <td className="px-4 py-3 text-center">{formatValue(prescription.spectacles.OD.add, true)}</td>
                      <td className="px-4 py-3 text-center">
                        {prescription.spectacles.OD.prism || '-'}
                        {prescription.spectacles.OD.prismBase && ` ${prescription.spectacles.OD.prismBase}`}
                      </td>
                      <td className="px-4 py-3 text-center">{prescription.spectacles.OD.pd} mm</td>
                    </tr>
                    <tr>
                      <td className="px-4 py-3 font-medium text-gray-900">OS (Left)</td>
                      <td className="px-4 py-3 text-center">{formatValue(prescription.spectacles.OS.sphere, true)}</td>
                      <td className="px-4 py-3 text-center">{formatValue(prescription.spectacles.OS.cylinder)}</td>
                      <td className="px-4 py-3 text-center">{prescription.spectacles.OS.axis}°</td>
                      <td className="px-4 py-3 text-center">{formatValue(prescription.spectacles.OS.add, true)}</td>
                      <td className="px-4 py-3 text-center">
                        {prescription.spectacles.OS.prism || '-'}
                        {prescription.spectacles.OS.prismBase && ` ${prescription.spectacles.OS.prismBase}`}
                      </td>
                      <td className="px-4 py-3 text-center">{prescription.spectacles.OS.pd} mm</td>
                    </tr>
                  </tbody>
                </table>
              </div>

              {/* Lens Details */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div className="p-3 bg-gray-50 rounded-lg">
                  <p className="text-sm text-gray-500">Lens Type</p>
                  <p className="font-medium capitalize">{prescription.spectacles.lensType || 'Single Vision'}</p>
                </div>
                <div className="p-3 bg-gray-50 rounded-lg">
                  <p className="text-sm text-gray-500">Lens Material</p>
                  <p className="font-medium capitalize">{prescription.spectacles.lensMaterial || 'CR-39'}</p>
                </div>
                <div className="p-3 bg-gray-50 rounded-lg">
                  <p className="text-sm text-gray-500">Tint</p>
                  <p className="font-medium capitalize">{prescription.spectacles.tint || 'Clear'}</p>
                </div>
                <div className="p-3 bg-gray-50 rounded-lg">
                  <p className="text-sm text-gray-500">Photochromic</p>
                  <p className="font-medium">{prescription.spectacles.photochromic ? 'Yes' : 'No'}</p>
                </div>
              </div>

              {/* Coatings */}
              {prescription.spectacles.lensCoatings && prescription.spectacles.lensCoatings.length > 0 && (
                <div className="mt-4">
                  <p className="text-sm text-gray-500 mb-2">Coatings</p>
                  <div className="flex flex-wrap gap-2">
                    {prescription.spectacles.lensCoatings.map((coating, index) => (
                      <span key={index} className="px-3 py-1 bg-teal-50 text-teal-700 rounded-full text-sm">
                        {coating.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Contact Lens Prescription */}
          {(prescription.type === 'contactLens' || prescription.type === 'both') && prescription.contactLens && (
            <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" />
                Contact Lens Prescription
              </h2>
              
              <div className="overflow-x-auto">
                <table className="min-w-full">
                  <thead>
                    <tr className="bg-gray-50">
                      <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">Eye</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Power</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">BC</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">DIA</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Cylinder</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Axis</th>
                      <th className="px-4 py-3 text-center text-sm font-medium text-gray-600">Brand</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    <tr>
                      <td className="px-4 py-3 font-medium text-gray-900">OD (Right)</td>
                      <td className="px-4 py-3 text-center">{formatValue(prescription.contactLens.OD.power, true)}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OD.baseCurve}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OD.diameter}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OD.cylinder || '-'}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OD.axis || '-'}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OD.brand || '-'}</td>
                    </tr>
                    <tr>
                      <td className="px-4 py-3 font-medium text-gray-900">OS (Left)</td>
                      <td className="px-4 py-3 text-center">{formatValue(prescription.contactLens.OS.power, true)}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OS.baseCurve}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OS.diameter}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OS.cylinder || '-'}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OS.axis || '-'}</td>
                      <td className="px-4 py-3 text-center">{prescription.contactLens.OS.brand || '-'}</td>
                    </tr>
                  </tbody>
                </table>
              </div>

              <div className="mt-4 grid grid-cols-2 gap-4">
                <div className="p-3 bg-gray-50 rounded-lg">
                  <p className="text-sm text-gray-500">Replacement Schedule</p>
                  <p className="font-medium capitalize">{prescription.contactLens.OD.modality || 'Monthly'}</p>
                </div>
              </div>
            </div>
          )}

          {/* Notes */}
          {prescription.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-teal-600" />
                Additional Notes
              </h2>
              <p className="text-gray-700 whitespace-pre-wrap">{prescription.notes}</p>
            </div>
          )}

          {/* Timestamps */}
          <div className="text-sm text-gray-500 text-center">
            <p>Created: {new Date(prescription.createdAt).toLocaleString()}</p>
            {prescription.updatedAt !== prescription.createdAt && (
              <p>Last Updated: {new Date(prescription.updatedAt).toLocaleString()}</p>
            )}
          </div>
        </div>
      </SidebarLayout>
    </ProtectedRoute>
  );
}
