'use client';

import { useEffect, useState } from 'react';
import {
  Search,
  MessageSquare,
  Mail,
  Calendar,
  TrendingUp,
  Activity,
  Phone,
} from 'lucide-react';
import { cn, formatPhone, relativeTime } from '@/lib/utils';

interface DashboardStats {
  activeConversations: number;
  messagesToday: number;
  bookingsMade: number;
  responseRate: number;
}

interface ActivityEvent {
  id: number;
  type: string;
  phone: string | null;
  name: string | null;
  bot_name: string | null;
  data_json: string | null;
  created_at: string;
  contact_id: string | null;
  route_id: string | null;
}

const statCards = [
  {
    key: 'activeConversations' as const,
    label: 'Contacts This Month',
    icon: MessageSquare,
    format: (v: number) => v.toLocaleString(),
    accent: 'cyan',
  },
  {
    key: 'messagesToday' as const,
    label: 'Messages This Month',
    icon: Mail,
    format: (v: number) => v.toLocaleString(),
    accent: 'blue',
  },
  {
    key: 'bookingsMade' as const,
    label: 'Bookings This Month',
    icon: Calendar,
    format: (v: number) => v.toLocaleString(),
    accent: 'green',
  },
  {
    key: 'responseRate' as const,
    label: 'Engagement Score',
    icon: TrendingUp,
    format: (v: number) => `${v}%`,
    accent: 'purple',
  },
];

const accentColors: Record<string, { icon: string; glow: string; bg: string }> = {
  cyan: {
    icon: 'text-cyan-400',
    glow: 'shadow-[0_0_20px_rgba(34,211,238,0.08)]  border-cyan-500/20',
    bg: 'bg-cyan-500/10',
  },
  blue: {
    icon: 'text-blue-400',
    glow: 'shadow-[0_0_20px_rgba(59,130,246,0.08)] border-blue-500/20',
    bg: 'bg-blue-500/10',
  },
  green: {
    icon: 'text-green-400',
    glow: 'shadow-[0_0_20px_rgba(34,197,94,0.08)] border-green-500/20',
    bg: 'bg-green-500/10',
  },
  purple: {
    icon: 'text-purple-400',
    glow: 'shadow-[0_0_20px_rgba(168,85,247,0.08)] border-purple-500/20',
    bg: 'bg-purple-500/10',
  },
};

function getStatusBadge(type: string) {
  switch (type) {
    case 'conversation_start':
    case 'message_received':
      return { label: 'Active', className: 'badge badge-active' };
    case 'message_sent':
    case 'bot_response':
      return { label: 'Pending', className: 'badge badge-pending' };
    case 'conversation_end':
      return { label: 'Closed', className: 'badge badge-closed' };
    default:
      return { label: type.replace(/_/g, ' '), className: 'badge badge-new' };
  }
}

export default function DashboardPage() {
  const [stats, setStats] = useState<DashboardStats>({
    activeConversations: 0,
    messagesToday: 0,
    bookingsMade: 0,
    responseRate: 0,
  });
  const [activity, setActivity] = useState<ActivityEvent[]>([]);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      try {
        const [statsRes, activityRes] = await Promise.all([
          fetch('/api/dashboard/stats'),
          fetch('/api/dashboard/activity'),
        ]);

        if (statsRes.ok) {
          const mergedStats = await statsRes.json();
          setStats(mergedStats);
        }

        if (activityRes.ok) {
          const data = await activityRes.json();
          setActivity(Array.isArray(data) ? data : data.events || []);
        }
      } catch (err) {
        console.error('Failed to fetch dashboard data:', err);
      } finally {
        setLoading(false);
      }
    }

    fetchData();

    // Set up SSE for real-time updates
    let eventSource: EventSource | null = null;
    try {
      eventSource = new EventSource('/api/dashboard/activity?stream=true');

      eventSource.addEventListener('activity', (e) => {
        try {
          const event = JSON.parse(e.data);
          setActivity((prev) => [event, ...prev].slice(0, 20));
        } catch {}
      });

      eventSource.addEventListener('stats', (e) => {
        try {
          const data = JSON.parse(e.data);
          setStats(data);
        } catch {}
      });

      eventSource.onerror = () => {
        eventSource?.close();
      };
    } catch {}

    return () => {
      eventSource?.close();
    };
  }, []);

  const filteredActivity = search
    ? activity.filter(
        (e) =>
          e.phone?.includes(search) ||
          e.name?.toLowerCase().includes(search.toLowerCase()) ||
          e.bot_name?.toLowerCase().includes(search.toLowerCase())
      )
    : activity;

  return (
    <div className="p-6 lg:p-8 space-y-6">
      {/* Header with search */}
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-white">Dashboard</h1>
          <p className="text-sm text-slate-500 mt-0.5">
            Real-time overview of your SMS operations
          </p>
        </div>
        <div className="relative w-80">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
          <input
            type="text"
            placeholder="Search conversations, contacts..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full rounded-lg border border-slate-700/50 bg-slate-800/50 py-2.5 pl-10 pr-4 text-sm text-slate-200 placeholder-slate-500 outline-none transition-colors focus:border-cyan-500/50 focus:ring-1 focus:ring-cyan-500/20 backdrop-blur-sm"
          />
        </div>
      </div>

      {/* Stat cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((card) => {
          const Icon = card.icon;
          const colors = accentColors[card.accent];
          const value = stats[card.key];

          return (
            <div
              key={card.key}
              className={cn(
                'card card-glow relative overflow-hidden p-5 transition-all duration-300 hover:scale-[1.02]',
                colors.glow
              )}
            >
              {/* Subtle gradient overlay */}
              <div className="absolute inset-0 bg-gradient-to-br from-white/[0.02] to-transparent pointer-events-none" />

              <div className="relative">
                <div className="flex items-center justify-between mb-3">
                  <div
                    className={cn(
                      'flex h-10 w-10 items-center justify-center rounded-lg',
                      colors.bg
                    )}
                  >
                    <Icon className={cn('h-5 w-5', colors.icon)} />
                  </div>
                </div>

                <p className="text-xs font-medium uppercase tracking-wider text-slate-500 mb-1">
                  {card.label}
                </p>

                <p className={cn('text-3xl font-bold num text-white')}>
                  {loading ? (
                    <span className="inline-block h-9 w-16 animate-pulse rounded bg-slate-700/50" />
                  ) : (
                    card.format(value)
                  )}
                </p>
              </div>
            </div>
          );
        })}
      </div>

      {/* Real-time Activity */}
      <div className="card overflow-hidden">
        <div className="flex items-center justify-between border-b border-slate-700/50 px-6 py-4">
          <div className="flex items-center gap-3">
            <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-cyan-500/10">
              <Activity className="h-4 w-4 text-cyan-400" />
            </div>
            <div>
              <h2 className="text-sm font-semibold text-white">
                Real-time Activity
              </h2>
              <p className="text-xs text-slate-500">
                Latest SMS events across all routes
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            <div className="h-2 w-2 rounded-full bg-green-500 animate-pulse" />
            <span className="text-xs text-slate-500">Live</span>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-slate-700/30">
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                  SMS
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                  Bot Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-slate-500">
                  Status
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium uppercase tracking-wider text-slate-500">
                  Timestamp
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-700/20">
              {loading ? (
                Array.from({ length: 5 }).map((_, i) => (
                  <tr key={i}>
                    <td className="px-6 py-4" colSpan={4}>
                      <div className="h-4 w-full animate-pulse rounded bg-slate-700/30" />
                    </td>
                  </tr>
                ))
              ) : filteredActivity.length === 0 ? (
                <tr>
                  <td
                    colSpan={4}
                    className="px-6 py-12 text-center text-sm text-slate-500"
                  >
                    <div className="flex flex-col items-center gap-3">
                      <MessageSquare className="h-8 w-8 text-slate-600" />
                      <div>
                        <p className="font-medium text-slate-400">
                          No activity yet
                        </p>
                        <p className="mt-1 text-xs text-slate-600">
                          Events will appear here as SMS conversations come in
                        </p>
                      </div>
                    </div>
                  </td>
                </tr>
              ) : (
                filteredActivity.map((event) => {
                  const badge = getStatusBadge(event.type);

                  return (
                    <tr
                      key={event.id}
                      className="transition-colors hover:bg-slate-800/30"
                    >
                      <td className="px-6 py-3.5">
                        <div className="flex items-center gap-3">
                          <div className="flex h-8 w-8 items-center justify-center rounded-full bg-slate-700/50">
                            <Phone className="h-3.5 w-3.5 text-slate-400" />
                          </div>
                          <div>
                            <p className="text-sm font-medium text-slate-200 num">
                              {event.phone
                                ? formatPhone(event.phone)
                                : 'Unknown'}
                            </p>
                            {event.name && (
                              <p className="text-xs text-slate-500">
                                {event.name}
                              </p>
                            )}
                          </div>
                        </div>
                      </td>
                      <td className="px-6 py-3.5">
                        <span className="text-sm text-slate-300">
                          {event.bot_name || '—'}
                        </span>
                      </td>
                      <td className="px-6 py-3.5">
                        <span className={badge.className}>{badge.label}</span>
                      </td>
                      <td className="px-6 py-3.5 text-right">
                        <span className="text-xs text-slate-500 num">
                          {relativeTime(event.created_at)}
                        </span>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
