import React, { useState, useEffect } from 'react';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, ReferenceLine } from 'recharts';
import { X, TrendingUp, TrendingDown, Activity, Heart, Wind, Thermometer } from 'lucide-react';

const API_BASE = `http://${window.location.hostname}:8000`;

const PatientDetailModal = ({ patient, onClose }) => {
  const [vitalsHistory, setVitalsHistory] = useState([]);
  const [tierChanges, setTierChanges] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedMetric, setSelectedMetric] = useState('all');

  useEffect(() => {
    fetchPatientHistory();
  }, [patient.patient_id]);

  const fetchPatientHistory = async () => {
    try {
      const response = await fetch(`${API_BASE}/api/patients/${patient.patient_id}/vitals-history?limit=200`);
      const data = await response.json();
      
      setVitalsHistory(data.vitals_history || []);
      setTierChanges(data.tier_changes || []);
      setLoading(false);
    } catch (error) {
      console.error('Failed to fetch patient history:', error);
      setLoading(false);
    }
  };

  const prepareChartData = () => {
    return vitalsHistory.slice().reverse().map((v, index) => ({
      time: index,
      timeLabel: new Date(v.timestamp * 1000).toLocaleTimeString(),
      hr: v.hr_bpm,
      spo2: v.spo2,
      temp: v.temp_c,
      tier: v.tier
    }));
  };

  const calculateTrend = (data, key) => {
    if (data.length < 2) return null;
    
    const recent = data.slice(-5);
    const first = recent[0][key];
    const last = recent[recent.length - 1][key];
    const change = last - first;
    
    return {
      direction: change > 0 ? 'up' : change < 0 ? 'down' : 'stable',
      value: Math.abs(change).toFixed(1)
    };
  };

  const chartData = prepareChartData();
  const hrTrend = calculateTrend(chartData, 'hr');
  const spo2Trend = calculateTrend(chartData, 'spo2');
  const tempTrend = calculateTrend(chartData, 'temp');

  if (loading) {
    return (
      <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div className="bg-white rounded-lg p-8">
          <Activity className="w-8 h-8 text-blue-600 animate-spin mx-auto" />
          <p className="text-gray-600 mt-4">Loading patient data...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl max-w-6xl w-full max-h-[90vh] overflow-y-auto">
        <div className="sticky top-0 bg-gradient-to-r from-blue-600 to-blue-700 text-white p-6 rounded-t-2xl flex justify-between items-start">
          <div>
            <h2 className="text-3xl font-bold mb-2">{patient.name}</h2>
            <div className="flex items-center gap-4 text-blue-100">
              <span className="font-mono">{patient.patient_id}</span>
              <span>•</span>
              <span className="font-mono">{patient.band_id}</span>
              <span>•</span>
              <span>Wait: {patient.wait_time_minutes} min</span>
            </div>
          </div>
          <button
            onClick={onClose}
            className="text-white hover:bg-white hover:bg-opacity-20 rounded-lg p-2 transition-colors"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        <div className="p-6">
          <div className="grid grid-cols-3 gap-4 mb-6">
            <div className="bg-blue-50 rounded-lg p-4 border-2 border-blue-200">
              <div className="flex items-center gap-2 mb-2">
                <Heart className="w-5 h-5 text-blue-600" />
                <span className="text-sm font-medium text-gray-600">Heart Rate</span>
              </div>
              <div className="flex items-end justify-between">
                <p className="text-3xl font-bold text-blue-600">{patient.last_hr}</p>
                <div className="text-right">
                  <p className="text-xs text-gray-500">bpm</p>
                  {hrTrend && (
                    <p className={`text-xs font-semibold flex items-center gap-1 ${
                      hrTrend.direction === 'up' ? 'text-red-600' : 
                      hrTrend.direction === 'down' ? 'text-green-600' : 'text-gray-600'
                    }`}>
                      {hrTrend.direction === 'up' ? <TrendingUp className="w-3 h-3" /> : 
                       hrTrend.direction === 'down' ? <TrendingDown className="w-3 h-3" /> : null}
                      {hrTrend.value}
                    </p>
                  )}
                </div>
              </div>
            </div>

            <div className="bg-green-50 rounded-lg p-4 border-2 border-green-200">
              <div className="flex items-center gap-2 mb-2">
                <Wind className="w-5 h-5 text-green-600" />
                <span className="text-sm font-medium text-gray-600">SpO₂</span>
              </div>
              <div className="flex items-end justify-between">
                <p className="text-3xl font-bold text-green-600">{patient.last_spo2}</p>
                <div className="text-right">
                  <p className="text-xs text-gray-500">%</p>
                  {spo2Trend && (
                    <p className={`text-xs font-semibold flex items-center gap-1 ${
                      spo2Trend.direction === 'down' ? 'text-red-600' : 
                      spo2Trend.direction === 'up' ? 'text-green-600' : 'text-gray-600'
                    }`}>
                      {spo2Trend.direction === 'up' ? <TrendingUp className="w-3 h-3" /> : 
                       spo2Trend.direction === 'down' ? <TrendingDown className="w-3 h-3" /> : null}
                      {spo2Trend.value}
                    </p>
                  )}
                </div>
              </div>
            </div>

            <div className="bg-orange-50 rounded-lg p-4 border-2 border-orange-200">
              <div className="flex items-center gap-2 mb-2">
                <Thermometer className="w-5 h-5 text-orange-600" />
                <span className="text-sm font-medium text-gray-600">Temperature</span>
              </div>
              <div className="flex items-end justify-between">
                <p className="text-3xl font-bold text-orange-600">{patient.last_temp.toFixed(1)}</p>
                <div className="text-right">
                  <p className="text-xs text-gray-500">°C</p>
                  {tempTrend && (
                    <p className={`text-xs font-semibold flex items-center gap-1 ${
                      tempTrend.direction === 'up' ? 'text-red-600' : 
                      tempTrend.direction === 'down' ? 'text-green-600' : 'text-gray-600'
                    }`}>
                      {tempTrend.direction === 'up' ? <TrendingUp className="w-3 h-3" /> : 
                       tempTrend.direction === 'down' ? <TrendingDown className="w-3 h-3" /> : null}
                      {tempTrend.value}
                    </p>
                  )}
                </div>
              </div>
            </div>
          </div>

          <div className="flex gap-2 mb-4">
            {['all', 'hr', 'spo2', 'temp'].map(metric => (
              <button
                key={metric}
                onClick={() => setSelectedMetric(metric)}
                className={`px-4 py-2 rounded-lg font-semibold ${
                  selectedMetric === metric ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700'
                }`}
              >
                {metric === 'all' ? 'All Vitals' :
                 metric === 'hr' ? 'Heart Rate' :
                 metric === 'spo2' ? 'SpO₂' : 'Temperature'}
              </button>
            ))}
          </div>

          {chartData.length > 0 ? (
            <div className="bg-white border-2 border-gray-200 rounded-lg p-4 mb-6">
              {(selectedMetric === 'all' || selectedMetric === 'hr') && (
                <div className="mb-6">
                  <h3 className="font-bold text-lg mb-3 flex items-center gap-2">
                    <Heart className="w-5 h-5 text-blue-600" />
                    Heart Rate Over Time
                  </h3>
                  <ResponsiveContainer width="100%" height={250}>
                    <LineChart data={chartData}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="timeLabel" tick={{fontSize: 12}} />
                      <YAxis domain={[40, 180]} label={{ value: 'BPM', angle: -90, position: 'insideLeft' }} />
                      <Tooltip />
                      <ReferenceLine y={110} stroke="#ef4444" strokeDasharray="3 3" label="ALERT" />
                      <ReferenceLine y={140} stroke="#dc2626" strokeDasharray="3 3" label="EMERGENCY" />
                      <Line type="monotone" dataKey="hr" stroke="#2563eb" strokeWidth={3} dot={{ r: 4 }} />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              )}

              {(selectedMetric === 'all' || selectedMetric === 'spo2') && (
                <div className="mb-6">
                  <h3 className="font-bold text-lg mb-3 flex items-center gap-2">
                    <Wind className="w-5 h-5 text-green-600" />
                    Oxygen Saturation Over Time
                  </h3>
                  <ResponsiveContainer width="100%" height={250}>
                    <LineChart data={chartData}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="timeLabel" tick={{fontSize: 12}} />
                      <YAxis domain={[70, 100]} label={{ value: '%', angle: -90, position: 'insideLeft' }} />
                      <Tooltip />
                      <ReferenceLine y={92} stroke="#eab308" strokeDasharray="3 3" label="ALERT" />
                      <ReferenceLine y={88} stroke="#dc2626" strokeDasharray="3 3" label="EMERGENCY" />
                      <Line type="monotone" dataKey="spo2" stroke="#16a34a" strokeWidth={3} dot={{ r: 4 }} />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              )}

              {(selectedMetric === 'all' || selectedMetric === 'temp') && (
                <div>
                  <h3 className="font-bold text-lg mb-3 flex items-center gap-2">
                    <Thermometer className="w-5 h-5 text-orange-600" />
                    Temperature Over Time
                  </h3>
                  <ResponsiveContainer width="100%" height={250}>
                    <LineChart data={chartData}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="timeLabel" tick={{fontSize: 12}} />
                      <YAxis domain={[35, 41]} label={{ value: '°C', angle: -90, position: 'insideLeft' }} />
                      <Tooltip />
                      <ReferenceLine y={38.3} stroke="#eab308" strokeDasharray="3 3" label="ALERT" />
                      <ReferenceLine y={39.5} stroke="#dc2626" strokeDasharray="3 3" label="EMERGENCY" />
                      <Line type="monotone" dataKey="temp" stroke="#ea580c" strokeWidth={3} dot={{ r: 4 }} />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              )}
            </div>
          ) : (
            <div className="bg-gray-50 rounded-lg p-12 text-center">
              <Activity className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <p className="text-gray-600">No vital signs history available yet</p>
            </div>
          )}

          {tierChanges.length > 0 && (
            <div className="bg-white border-2 border-gray-200 rounded-lg p-4 mt-4">
              <h3 className="font-bold text-lg mb-3">Tier Change History</h3>
              <div className="space-y-2">
                {tierChanges.map((change, index) => (
                  <div key={index} className="flex items-center gap-3 p-3 bg-gray-50 rounded">
                    <span className="text-sm text-gray-500">
                      {new Date(change.change_time).toLocaleTimeString()}
                    </span>
                    <span className="text-sm font-semibold">{change.old_tier}</span>
                    <span>→</span>
                    <span className="text-sm font-semibold text-red-600">{change.new_tier}</span>
                    <span className="text-xs text-gray-600">({change.reason})</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          <div className="mt-6 grid grid-cols-3 gap-4">
            <div className="bg-gray-50 rounded-lg p-4">
              <p className="text-sm text-gray-600">Total Readings</p>
              <p className="text-2xl font-bold">{vitalsHistory.length}</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-4">
              <p className="text-sm text-gray-600">Priority Score</p>
              <p className="text-2xl font-bold">{patient.priority_score.toFixed(1)}</p>
            </div>
            <div className="bg-gray-50 rounded-lg p-4">
              <p className="text-sm text-gray-600">Current Tier</p>
              <p className={`text-2xl font-bold ${
                patient.tier === 'EMERGENCY' ? 'text-red-600' :
                patient.tier === 'ALERT' ? 'text-yellow-600' : 'text-green-600'
              }`}>
                {patient.tier}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PatientDetailModal;
