'use client'

import { useState, useEffect } from 'react'
import { 
  AlertTriangle, Phone, X, Heart, 
  User, Droplet, AlertCircle, MapPin 
} from 'lucide-react'

import { useApp } from '../provider'

interface EmergencyWidgetProps {
  workspaceId: string
}

export function EmergencyWidget({ workspaceId }: EmergencyWidgetProps) {
  const [isOpen, setIsOpen] = useState(false)
  const [emergencyInfo, setEmergencyInfo] = useState<any>(null)
  const { currentWorkspace } = useApp()

  useEffect(() => {
    const fetchInfo = async () => {
      try {
        const response = await fetch(`/api/workspaces/${workspaceId}/emergency-info`)
        if (response.ok) {
          const data = await response.json()
          setEmergencyInfo(data.info)
        }
      } catch (err) {
        console.error('Failed to fetch emergency info:', err)
      }
    }
    fetchInfo()
  }, [workspaceId])

  if (!emergencyInfo) return null

  const hasAnyInfo = emergencyInfo.patientName || 
    emergencyInfo.bloodType || 
    emergencyInfo.allergies || 
    emergencyInfo.medicalConditions ||
    emergencyInfo.clinicPhone ||
    emergencyInfo.emergencyPhone

  if (!hasAnyInfo) return null

  return (
    <>
      {/* Floating Emergency Button */}
      <button
        onClick={() => setIsOpen(true)}
        className="fixed bottom-20 right-4 z-40 w-14 h-14 rounded-full bg-red-600 text-white shadow-lg hover:bg-red-700 transition-all hover:scale-110 flex items-center justify-center"
        title="Emergency Info"
      >
        <AlertTriangle className="w-6 h-6" />
      </button>

      {/* Emergency Modal */}
      {isOpen && (
        <div className="fixed inset-0 bg-black/60 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">
          <div className="bg-white w-full max-w-md rounded-t-2xl sm:rounded-2xl max-h-[90vh] overflow-auto animate-in slide-in-from-bottom duration-200">
            {/* Header */}
            <div className="sticky top-0 bg-red-600 text-white p-4 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <AlertTriangle className="w-6 h-6" />
                <h2 className="text-lg font-semibold">Emergency Info</h2>
              </div>
              <button 
                onClick={() => setIsOpen(false)}
                className="p-2 hover:bg-red-700 rounded-full"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-4 space-y-4">
              {/* Quick Call Buttons */}
              <div className="grid grid-cols-2 gap-3">
                {emergencyInfo.emergencyPhone && (
                  <a
                    href={`tel:${emergencyInfo.emergencyPhone}`}
                    className="bg-red-100 border border-red-200 rounded-xl p-4 text-center hover:bg-red-200 transition-colors"
                  >
                    <Phone className="w-8 h-8 text-red-600 mx-auto mb-2" />
                    <p className="font-semibold text-red-800">Emergency</p>
                    <p className="text-sm text-red-600">{emergencyInfo.emergencyPhone}</p>
                  </a>
                )}
                {emergencyInfo.clinicPhone && (
                  <a
                    href={`tel:${emergencyInfo.clinicPhone}`}
                    className="bg-blue-100 border border-blue-200 rounded-xl p-4 text-center hover:bg-blue-200 transition-colors"
                  >
                    <Heart className="w-8 h-8 text-blue-600 mx-auto mb-2" />
                    <p className="font-semibold text-blue-800">Clinic</p>
                    <p className="text-sm text-blue-600">{emergencyInfo.clinicPhone}</p>
                  </a>
                )}
                {emergencyInfo.physicianPhone && (
                  <a
                    href={`tel:${emergencyInfo.physicianPhone}`}
                    className="bg-green-100 border border-green-200 rounded-xl p-4 text-center hover:bg-green-200 transition-colors col-span-2"
                  >
                    <User className="w-8 h-8 text-green-600 mx-auto mb-2" />
                    <p className="font-semibold text-green-800">Primary Physician</p>
                    <p className="text-sm text-green-600">{emergencyInfo.physicianPhone}</p>
                    {emergencyInfo.primaryPhysician && (
                      <p className="text-xs text-green-500 mt-1">
                        Dr. {emergencyInfo.primaryPhysician}
                      </p>
                    )}
                  </a>
                )}
              </div>

              {/* Medical ID Card */}
              <div className="bg-amber-50 border-2 border-amber-200 rounded-xl p-4">
                <div className="flex items-center gap-2 mb-3">
                  <AlertCircle className="w-5 h-5 text-amber-600" />
                  <h3 className="font-semibold text-amber-900">Medical ID</h3>
                </div>
                
                <div className="space-y-2">
                  {emergencyInfo.patientName && (
                    <div className="flex items-center gap-2">
                      <User className="w-4 h-4 text-amber-600" />
                      <span className="text-amber-900">
                        <strong>Name:</strong> {emergencyInfo.patientName}
                      </span>
                    </div>
                  )}
                  {emergencyInfo.bloodType && (
                    <div className="flex items-center gap-2">
                      <Droplet className="w-4 h-4 text-amber-600" />
                      <span className="text-amber-900">
                        <strong>Blood Type:</strong> {emergencyInfo.bloodType}
                      </span>
                    </div>
                  )}
                  {emergencyInfo.allergies && (
                    <div className="flex items-start gap-2">
                      <AlertCircle className="w-4 h-4 text-red-500 mt-0.5" />
                      <div>
                        <span className="text-red-700 font-medium">Allergies:</span>
                        <p className="text-red-600">{emergencyInfo.allergies}</p>
                      </div>
                    </div>
                  )}
                  {emergencyInfo.medicalConditions && (
                    <div className="flex items-start gap-2">
                      <Heart className="w-4 h-4 text-amber-600 mt-0.5" />
                      <div>
                        <span className="text-amber-900 font-medium">Conditions:</span>
                        <p className="text-amber-800">{emergencyInfo.medicalConditions}</p>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* Current Medications */}
              {emergencyInfo.medications?.length > 0 && (
                <div className="bg-blue-50 border border-blue-200 rounded-xl p-4">
                  <h3 className="font-semibold text-blue-900 mb-2">Current Medications</h3>
                  <ul className="space-y-1">
                    {emergencyInfo.medications.map((med: any) => (
                      <li key={med.id} className="text-sm text-blue-800">
                        • {med.name} {med.instructions && `(${med.instructions})`}
                      </li>
                    ))}
                  </ul>
                </div>
              )}

              {/* Edit Button */}
              {currentWorkspace.role !== 'VIEWER' && (
                <a
                  href="/settings/emergency"
                  className="block w-full py-3 text-center text-secondary-600 hover:text-secondary-900 text-sm"
                >
                  Edit Emergency Information
                </a>
              )}

              {/* Disclaimer */}
              <p className="text-xs text-secondary-400 text-center">
                This information is for emergency use only. 
                Always call 000 (AU) or your local emergency number in a life-threatening emergency.
              </p>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
