'use client';

import { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import Link from 'next/link';
import {
  Video,
  Phone,
  MessageCircle,
  Clock,
  Users,
  Calendar,
  CheckCircle,
  XCircle,
  AlertCircle,
  Plus,
  ArrowRight,
  Activity,
  TrendingUp,
  MonitorPlay,
} from 'lucide-react';
import SidebarLayout from '../components/sidebar-layout';

interface Session {
  _id: string;
  sessionNumber: string;
  patientId: {
    _id: string;
    name: string;
    patientId: string;
    profilePhoto?: string;
  };
  doctorId: {
    _id: string;
    name: string;
    specialization?: string;
    profilePhoto?: string;
  };
  consultationType: 'video' | 'audio' | 'chat';
  scheduledStartTime: string;
  scheduledEndTime: string;
  status: string;
}

interface Stats {
  todayCount: number;
  inProgress: number;
  waiting: number;
  byType: { _id: string; count: number }[];
  byStatus: { _id: string; count: number }[];
}

export default function TelemedicineDashboard() {
  const { data: authSession } = useSession();
  const [sessions, setSessions] = useState<Session[]>([]);
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchDashboardData();
    // Refresh every 30 seconds
    const interval = setInterval(fetchDashboardData, 30000);
    return () => clearInterval(interval);
  }, []);

  const fetchDashboardData = async () => {
    try {
      const [todayRes, upcomingRes] = await Promise.all([
        fetch('/api/telemedicine/sessions?today=true&limit=50'),
        fetch('/api/telemedicine/sessions?upcoming=true&limit=10'),
      ]);

      if (!todayRes.ok || !upcomingRes.ok) {
        throw new Error('Failed to fetch data');
      }

      const todayData = await todayRes.json();
      const upcomingData = await upcomingRes.json();

      setSessions([...todayData.sessions]);
      setStats(todayData.stats);
      setLoading(false);
    } catch (err) {
      setError('Failed to load telemedicine data');
      setLoading(false);
    }
  };

  const getConsultationIcon = (type: string) => {
    switch (type) {
      case 'video':
        return <Video className="w-4 h-4" />;
      case 'audio':
        return <Phone className="w-4 h-4" />;
      case 'chat':
        return <MessageCircle className="w-4 h-4" />;
      default:
        return <Video className="w-4 h-4" />;
    }
  };

  const getStatusBadge = (status: string) => {
    const styles: Record<string, string> = {
      'scheduled': 'bg-blue-100 text-blue-800',
      'waiting': 'bg-yellow-100 text-yellow-800',
      'in-progress': 'bg-green-100 text-green-800',
      'completed': 'bg-gray-100 text-gray-800',
      'cancelled': 'bg-red-100 text-red-800',
      'no-show': 'bg-orange-100 text-orange-800',
      'technical-issue': 'bg-purple-100 text-purple-800',
    };
    return styles[status] || 'bg-gray-100 text-gray-800';
  };

  const formatTime = (dateString: string) => {
    return new Date(dateString).toLocaleTimeString('en-US', {
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const activeSessions = sessions.filter(s => s.status === 'in-progress');
  const waitingSessions = sessions.filter(s => s.status === 'waiting');
  const upcomingSessions = sessions.filter(s => s.status === 'scheduled');

  if (loading) {
    return (
      <SidebarLayout title="Telemedicine" description="Virtual consultations dashboard">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        </div>
      </SidebarLayout>
    );
  }

  return (
    <SidebarLayout title="Telemedicine" description="Virtual consultations dashboard">
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col sm:flex-row gap-4 justify-between">
          <div />
          <Link
            href="/telemedicine/sessions/new"
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            <Plus className="w-5 h-5" />
            New Session
          </Link>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-white rounded-lg shadow-sm p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
                <Calendar className="h-5 w-5 text-blue-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">Today's Sessions</p>
                <p className="text-2xl font-bold">{stats?.todayCount || 0}</p>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
                <Activity className="h-5 w-5 text-green-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">Active Now</p>
                <p className="text-2xl font-bold text-green-600">{stats?.inProgress || 0}</p>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-yellow-100 rounded-full flex items-center justify-center">
                <Clock className="h-5 w-5 text-yellow-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">Waiting</p>
                <p className="text-2xl font-bold text-yellow-600">{stats?.waiting || 0}</p>
              </div>
            </div>
          </div>

          <div className="bg-white rounded-lg shadow-sm p-4">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 bg-purple-100 rounded-full flex items-center justify-center">
                <Video className="h-5 w-5 text-purple-600" />
              </div>
              <div>
                <p className="text-sm text-gray-500">Video Calls</p>
                <p className="text-2xl font-bold text-purple-600">
                  {stats?.byType?.find(t => t._id === 'video')?.count || 0}
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Active Sessions */}
        {activeSessions.length > 0 && (
          <div className="bg-green-50 border border-green-200 rounded-lg p-6">
            <div className="flex items-center gap-2 mb-4">
              <MonitorPlay className="w-5 h-5 text-green-600" />
              <h2 className="text-lg font-semibold text-green-800">Active Sessions</h2>
              <span className="bg-green-600 text-white text-xs px-2 py-1 rounded-full">
                {activeSessions.length} Live
              </span>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {activeSessions.map(session => (
                <Link
                  key={session._id}
                  href={`/telemedicine/sessions/${session._id}`}
                  className="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow border border-green-200"
                >
                  <div className="flex items-center justify-between mb-2">
                    <span className="text-sm font-medium text-gray-900">
                      {session.sessionNumber}
                    </span>
                    <span className="flex items-center gap-1 text-green-600 text-sm">
                      {getConsultationIcon(session.consultationType)}
                      {session.consultationType}
                    </span>
                  </div>
                  <p className="font-semibold text-gray-900">
                    {session.patientId.name}
                  </p>
                  <p className="text-sm text-gray-600">
                    with Dr. {session.doctorId.name}
                  </p>
                  <div className="mt-2 flex items-center gap-2 text-green-600 text-sm font-medium">
                    <span className="relative flex h-2 w-2">
                      <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                      <span className="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
                    </span>
                    In Progress
                  </div>
                </Link>
              ))}
            </div>
          </div>
        )}

        {/* Waiting Room */}
        {waitingSessions.length > 0 && (
          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-6">
            <div className="flex items-center gap-2 mb-4">
              <Clock className="w-5 h-5 text-yellow-600" />
              <h2 className="text-lg font-semibold text-yellow-800">Waiting Room</h2>
              <span className="bg-yellow-600 text-white text-xs px-2 py-1 rounded-full">
                {waitingSessions.length} waiting
              </span>
            </div>
            <div className="space-y-3">
              {waitingSessions.map(session => (
                <div
                  key={session._id}
                  className="bg-white rounded-lg p-4 flex items-center justify-between border border-yellow-200"
                >
                  <div className="flex items-center gap-4">
                    <div className="w-10 h-10 bg-yellow-100 rounded-full flex items-center justify-center">
                      {getConsultationIcon(session.consultationType)}
                    </div>
                    <div>
                      <p className="font-semibold text-gray-900">
                        {session.patientId.name}
                      </p>
                      <p className="text-sm text-gray-600">
                        Waiting for Dr. {session.doctorId.name}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-4">
                    <span className="text-sm text-gray-500">
                      Scheduled: {formatTime(session.scheduledStartTime)}
                    </span>
                    <Link
                      href={`/telemedicine/sessions/${session._id}`}
                      className="bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors"
                    >
                      Join Now
                    </Link>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Upcoming Sessions */}
        <div className="bg-white rounded-lg shadow-sm overflow-hidden">
          <div className="p-6 border-b border-gray-200">
            <div className="flex items-center justify-between">
              <h2 className="text-lg font-semibold text-gray-900">Today's Schedule</h2>
              <Link
                href="/telemedicine/sessions"
                className="text-blue-600 hover:text-blue-700 text-sm font-medium flex items-center gap-1"
              >
                View All <ArrowRight className="w-4 h-4" />
              </Link>
            </div>
          </div>
          <div className="divide-y divide-gray-200">
            {sessions.length === 0 ? (
              <div className="p-12 text-center">
                <Video className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                <p className="text-gray-500">No telemedicine sessions scheduled for today</p>
                <Link
                  href="/telemedicine/sessions/new"
                  className="mt-4 inline-flex items-center gap-2 text-blue-600 hover:text-blue-700 font-medium"
                >
                  <Plus className="w-4 h-4" />
                  Schedule a Session
                </Link>
              </div>
            ) : (
              sessions.map(session => (
                <Link
                  key={session._id}
                  href={`/telemedicine/sessions/${session._id}`}
                  className="p-4 hover:bg-gray-50 flex items-center justify-between transition-colors"
                >
                  <div className="flex items-center gap-4">
                    <div className="flex flex-col items-center text-center min-w-[60px]">
                      <span className="text-lg font-bold text-gray-900">
                        {formatTime(session.scheduledStartTime)}
                      </span>
                      <span className="text-xs text-gray-500">
                        {formatTime(session.scheduledEndTime)}
                      </span>
                    </div>
                    <div className="w-px h-12 bg-gray-200"></div>
                    <div className="flex items-center gap-3">
                      <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                        session.consultationType === 'video' ? 'bg-blue-100 text-blue-600' :
                        session.consultationType === 'audio' ? 'bg-green-100 text-green-600' :
                        'bg-purple-100 text-purple-600'
                      }`}>
                        {getConsultationIcon(session.consultationType)}
                      </div>
                      <div>
                        <p className="font-medium text-gray-900">
                          {session.patientId.name}
                        </p>
                        <p className="text-sm text-gray-500">
                          Dr. {session.doctorId.name} • {session.doctorId.specialization || 'General'}
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="flex items-center gap-4">
                    <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusBadge(session.status)}`}>
                      {session.status.replace('-', ' ')}
                    </span>
                    <ArrowRight className="w-5 h-5 text-gray-400" />
                  </div>
                </Link>
              ))
            )}
          </div>
        </div>

        {/* Quick Actions */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <Link
            href="/telemedicine/sessions/new"
            className="bg-white rounded-lg shadow-sm p-6 hover:shadow-md transition-all group border border-gray-200"
          >
            <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mb-4 group-hover:bg-blue-200 transition-colors">
              <Video className="w-6 h-6 text-blue-600" />
            </div>
            <h3 className="font-semibold text-gray-900 mb-1">Start Video Call</h3>
            <p className="text-sm text-gray-500">Schedule or start an instant video consultation</p>
          </Link>

          <Link
            href="/telemedicine/waiting-room"
            className="bg-white rounded-lg shadow-sm p-6 hover:shadow-md transition-all group border border-gray-200"
          >
            <div className="w-12 h-12 bg-yellow-100 rounded-full flex items-center justify-center mb-4 group-hover:bg-yellow-200 transition-colors">
              <Users className="w-6 h-6 text-yellow-600" />
            </div>
            <h3 className="font-semibold text-gray-900 mb-1">Waiting Room</h3>
            <p className="text-sm text-gray-500">View patients waiting for consultation</p>
          </Link>

          <Link
            href="/telemedicine/sessions?status=completed"
            className="bg-white rounded-lg shadow-sm p-6 hover:shadow-md transition-all group border border-gray-200"
          >
            <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mb-4 group-hover:bg-green-200 transition-colors">
              <CheckCircle className="w-6 h-6 text-green-600" />
            </div>
            <h3 className="font-semibold text-gray-900 mb-1">Completed Sessions</h3>
            <p className="text-sm text-gray-500">Review past consultations and notes</p>
          </Link>
        </div>
      </div>
    </SidebarLayout>
  );
}
