import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { api } from '@/lib/api';
import type { Client, Event, Email, InsightsData } from '@/types';
import type { Interaction } from '@/types';
import { Users, Calendar, Mail, Plus, ArrowRight, Gift, Heart, Clock, AlertTriangle, Sparkles, UserCheck, PhoneForwarded, Star, Phone, FileText, MoreHorizontal } from 'lucide-react';
import { formatDate, getDaysUntil, getInitials } from '@/lib/utils';
import { EventTypeBadge } from '@/components/Badge';
import { PageLoader } from '@/components/LoadingSpinner';
import { usePinnedClients } from '@/hooks/usePinnedClients';

export default function DashboardPage() {
  const [clients, setClients] = useState<Client[]>([]);
  const [events, setEvents] = useState<Event[]>([]);
  const [emails, setEmails] = useState<Email[]>([]);
  const [insights, setInsights] = useState<InsightsData | null>(null);
  const [recentInteractions, setRecentInteractions] = useState<Interaction[]>([]);
  const [loading, setLoading] = useState(true);
  const { pinnedIds, togglePin, isPinned } = usePinnedClients();

  useEffect(() => {
    Promise.all([
      api.getClients().catch(() => []),
      api.getEvents({ upcoming: 7 }).catch(() => []),
      api.getEmails({ status: 'draft' }).catch(() => []),
      api.getInsights().catch(() => null),
      api.getRecentInteractions(5).catch(() => []),
    ]).then(([c, e, em, ins, ri]) => {
      setClients(c);
      setEvents(e);
      setEmails(em);
      setInsights(ins as InsightsData | null);
      setRecentInteractions(ri as Interaction[]);
      setLoading(false);
    });
  }, []);

  if (loading) return <PageLoader />;

  const pinnedClients = clients.filter((c) => pinnedIds.includes(c.id));

  const stats = [
    { label: 'Total Clients', value: clients.length, icon: Users, color: 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400', link: '/clients' },
    { label: 'Upcoming Events', value: events.length, icon: Calendar, color: 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400', link: '/events' },
    { label: 'Pending Drafts', value: emails.length, icon: Mail, color: 'bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400', link: '/emails' },
  ];

  const eventIcon = (type: string) => {
    if (type === 'birthday') return <Gift className="w-4 h-4 text-pink-500" />;
    if (type === 'anniversary') return <Heart className="w-4 h-4 text-purple-500" />;
    return <Clock className="w-4 h-4 text-blue-500" />;
  };

  return (
    <div className="max-w-6xl mx-auto space-y-6 animate-fade-in">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100">Dashboard</h1>
          <p className="text-slate-500 dark:text-slate-400 text-sm mt-1">Welcome back. Here's your overview.</p>
        </div>
        <Link
          to="/clients"
          state={{ openCreate: true }}
          className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors"
        >
          <Plus className="w-4 h-4" />
          Add Client
        </Link>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {stats.map((stat) => (
          <Link
            key={stat.label}
            to={stat.link}
            className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl p-5 hover:shadow-md dark:hover:shadow-slate-900/50 transition-shadow"
          >
            <div className="flex items-center gap-3">
              <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${stat.color}`}>
                <stat.icon className="w-5 h-5" />
              </div>
              <div>
                <p className="text-2xl font-bold text-slate-900 dark:text-slate-100">{stat.value}</p>
                <p className="text-sm text-slate-500 dark:text-slate-400">{stat.label}</p>
              </div>
            </div>
          </Link>
        ))}
      </div>

      {/* Pinned Clients */}
      {pinnedClients.length > 0 && (
        <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl">
          <div className="flex items-center gap-2 px-5 py-4 border-b border-slate-100 dark:border-slate-700">
            <Star className="w-4 h-4 text-amber-500 fill-amber-500" />
            <h2 className="font-semibold text-slate-900 dark:text-slate-100">Pinned Clients</h2>
          </div>
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3 p-4">
            {pinnedClients.map((client) => (
              <Link
                key={client.id}
                to={`/clients/${client.id}`}
                className="flex items-center gap-3 p-3 rounded-lg bg-slate-50 dark:bg-slate-700/50 hover:bg-slate-100 dark:hover:bg-slate-700 transition-colors group"
              >
                <div className="w-9 h-9 bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0">
                  {getInitials(client.firstName, client.lastName)}
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
                    {client.firstName} {client.lastName}
                  </p>
                  <p className="text-xs text-slate-500 dark:text-slate-400 truncate">
                    {client.company || 'No company'}
                  </p>
                </div>
              </Link>
            ))}
          </div>
        </div>
      )}

      {/* AI Insights */}
      {insights && (insights.staleClients.length > 0 || insights.upcomingBirthdays.length > 0 || insights.suggestedFollowups.length > 0) && (
        <div className="bg-gradient-to-br from-indigo-50 to-purple-50 dark:from-indigo-900/20 dark:to-purple-900/20 border border-indigo-200 dark:border-indigo-800 rounded-xl p-5 space-y-4">
          <div className="flex items-center gap-2">
            <Sparkles className="w-5 h-5 text-indigo-600 dark:text-indigo-400" />
            <h2 className="font-semibold text-indigo-900 dark:text-indigo-200">AI Insights</h2>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
            {insights.staleClients.length > 0 && (
              <div className="bg-white/80 dark:bg-slate-800/80 rounded-lg p-4 space-y-3">
                <div className="flex items-center gap-2 text-sm font-medium text-red-700 dark:text-red-400">
                  <AlertTriangle className="w-4 h-4" />
                  Needs Attention
                </div>
                <p className="text-xs text-slate-500 dark:text-slate-400">
                  {insights.summary.staleCount} client{insights.summary.staleCount !== 1 ? 's' : ''} not contacted in 30+ days
                  {insights.summary.neverContacted > 0 && `, ${insights.summary.neverContacted} never contacted`}
                </p>
                <div className="space-y-2">
                  {insights.staleClients.slice(0, 3).map(c => (
                    <Link key={c.id} to={`/clients/${c.id}`} className="flex items-center gap-2 group">
                      <div className="w-6 h-6 bg-red-100 dark:bg-red-900/50 text-red-700 dark:text-red-300 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0">
                        {c.firstName[0]}{c.lastName[0]}
                      </div>
                      <div className="min-w-0">
                        <p className="text-xs font-medium text-slate-700 dark:text-slate-300 truncate group-hover:text-blue-600 dark:group-hover:text-blue-400">
                          {c.firstName} {c.lastName}
                        </p>
                        <p className="text-xs text-slate-400">
                          {c.daysSinceContact ? `${c.daysSinceContact}d ago` : 'Never contacted'}
                        </p>
                      </div>
                    </Link>
                  ))}
                  {insights.staleClients.length > 3 && (
                    <Link to="/clients" className="text-xs text-indigo-600 dark:text-indigo-400 hover:text-indigo-700">
                      +{insights.staleClients.length - 3} more
                    </Link>
                  )}
                </div>
              </div>
            )}

            {insights.upcomingBirthdays.length > 0 && (
              <div className="bg-white/80 dark:bg-slate-800/80 rounded-lg p-4 space-y-3">
                <div className="flex items-center gap-2 text-sm font-medium text-pink-700 dark:text-pink-400">
                  <Gift className="w-4 h-4" />
                  Birthdays This Week
                </div>
                <div className="space-y-2">
                  {insights.upcomingBirthdays.map(c => (
                    <Link key={c.id} to={`/clients/${c.id}`} className="flex items-center gap-2 group">
                      <div className="w-6 h-6 bg-pink-100 dark:bg-pink-900/50 text-pink-700 dark:text-pink-300 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0">
                        🎂
                      </div>
                      <div className="min-w-0">
                        <p className="text-xs font-medium text-slate-700 dark:text-slate-300 truncate group-hover:text-blue-600 dark:group-hover:text-blue-400">
                          {c.firstName} {c.lastName}
                        </p>
                        <p className="text-xs text-slate-400">
                          {c.daysUntil === 0 ? 'Today!' : c.daysUntil === 1 ? 'Tomorrow' : `In ${c.daysUntil} days`}
                        </p>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            )}

            {insights.suggestedFollowups.length > 0 && (
              <div className="bg-white/80 dark:bg-slate-800/80 rounded-lg p-4 space-y-3">
                <div className="flex items-center gap-2 text-sm font-medium text-amber-700 dark:text-amber-400">
                  <PhoneForwarded className="w-4 h-4" />
                  Suggested Follow-ups
                </div>
                <p className="text-xs text-slate-500 dark:text-slate-400">
                  Contacted 14-30 days ago — good time to reach out
                </p>
                <div className="space-y-2">
                  {insights.suggestedFollowups.slice(0, 3).map(c => (
                    <Link key={c.id} to={`/clients/${c.id}`} className="flex items-center gap-2 group">
                      <div className="w-6 h-6 bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-300 rounded-full flex items-center justify-center text-xs font-bold flex-shrink-0">
                        {c.firstName[0]}{c.lastName[0]}
                      </div>
                      <div className="min-w-0">
                        <p className="text-xs font-medium text-slate-700 dark:text-slate-300 truncate group-hover:text-blue-600 dark:group-hover:text-blue-400">
                          {c.firstName} {c.lastName}
                        </p>
                        <p className="text-xs text-slate-400">
                          {c.daysSinceContact}d since last contact
                        </p>
                      </div>
                    </Link>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Upcoming Events */}
        <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl">
          <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-slate-700">
            <h2 className="font-semibold text-slate-900 dark:text-slate-100">Upcoming Events</h2>
            <Link to="/events" className="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 flex items-center gap-1">
              View all <ArrowRight className="w-3.5 h-3.5" />
            </Link>
          </div>
          <div className="divide-y divide-slate-100 dark:divide-slate-700">
            {events.length === 0 ? (
              <p className="px-5 py-8 text-center text-sm text-slate-400">No upcoming events</p>
            ) : (
              events.slice(0, 5).map((event) => (
                <div key={event.id} className="flex items-center gap-3 px-5 py-3">
                  {eventIcon(event.type)}
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">{event.title}</p>
                    <p className="text-xs text-slate-500 dark:text-slate-400">{formatDate(event.date)}</p>
                  </div>
                  <EventTypeBadge type={event.type} />
                  <span className="text-xs text-slate-400 whitespace-nowrap">
                    {getDaysUntil(event.date)}d
                  </span>
                </div>
              ))
            )}
          </div>
        </div>

        {/* Recent Interactions */}
        <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl">
          <div className="flex items-center gap-2 px-5 py-4 border-b border-slate-100 dark:border-slate-700">
            <Phone className="w-4 h-4 text-indigo-500" />
            <h2 className="font-semibold text-slate-900 dark:text-slate-100">Recent Interactions</h2>
          </div>
          <div className="divide-y divide-slate-100 dark:divide-slate-700">
            {recentInteractions.length === 0 ? (
              <p className="px-5 py-8 text-center text-sm text-slate-400 dark:text-slate-500">No interactions logged yet</p>
            ) : (
              recentInteractions.map((interaction) => {
                const typeIcons: Record<string, typeof Phone> = {
                  call: Phone, meeting: Users, email: Mail, note: FileText, other: MoreHorizontal,
                };
                const typeColors: Record<string, string> = {
                  call: 'text-green-600 dark:text-green-400', meeting: 'text-blue-600 dark:text-blue-400',
                  email: 'text-purple-600 dark:text-purple-400', note: 'text-amber-600 dark:text-amber-400', other: 'text-slate-500',
                };
                const Icon = typeIcons[interaction.type] || MoreHorizontal;
                return (
                  <Link
                    key={interaction.id}
                    to={`/clients/${interaction.clientId}`}
                    className="flex items-center gap-3 px-5 py-3 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
                  >
                    <Icon className={`w-4 h-4 ${typeColors[interaction.type] || 'text-slate-400'}`} />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">{interaction.title}</p>
                      <p className="text-xs text-slate-500 dark:text-slate-400 truncate">
                        {interaction.client ? `${interaction.client.firstName} ${interaction.client.lastName}` : ''}
                        {interaction.duration ? ` · ${interaction.duration}min` : ''}
                      </p>
                    </div>
                    <span className="text-xs text-slate-400 dark:text-slate-500 whitespace-nowrap">
                      {formatDate(interaction.contactedAt)}
                    </span>
                  </Link>
                );
              })
            )}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 gap-6">
        {/* Recent Clients */}
        <div className="bg-white dark:bg-slate-800 border border-slate-200 dark:border-slate-700 rounded-xl">
          <div className="flex items-center justify-between px-5 py-4 border-b border-slate-100 dark:border-slate-700">
            <h2 className="font-semibold text-slate-900 dark:text-slate-100">Recent Clients</h2>
            <Link to="/clients" className="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 flex items-center gap-1">
              View all <ArrowRight className="w-3.5 h-3.5" />
            </Link>
          </div>
          <div className="divide-y divide-slate-100 dark:divide-slate-700">
            {clients.length === 0 ? (
              <p className="px-5 py-8 text-center text-sm text-slate-400">No clients yet</p>
            ) : (
              [...clients]
                .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
                .slice(0, 5)
                .map((client) => (
                  <Link
                    key={client.id}
                    to={`/clients/${client.id}`}
                    className="flex items-center gap-3 px-5 py-3 hover:bg-slate-50 dark:hover:bg-slate-700/50 transition-colors"
                  >
                    <div className="w-9 h-9 bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0">
                      {client.firstName[0]}{client.lastName[0]}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-slate-900 dark:text-slate-100 truncate">
                        {client.firstName} {client.lastName}
                      </p>
                      <p className="text-xs text-slate-500 dark:text-slate-400 truncate">
                        {client.company || client.email || 'No details'}
                      </p>
                    </div>
                    <button
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        togglePin(client.id);
                      }}
                      className="p-1 rounded text-slate-300 hover:text-amber-500 transition-colors"
                      title={isPinned(client.id) ? 'Unpin' : 'Pin to dashboard'}
                    >
                      <Star className={`w-4 h-4 ${isPinned(client.id) ? 'text-amber-500 fill-amber-500' : ''}`} />
                    </button>
                  </Link>
                ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
