import { Card, CardContent, CardHeader, Avatar, Chip, Button, ScrollShadow } from '@heroui/react';
import {
  Bot, CalendarDays, Users, Ticket, Shield, MessageSquare,
  ChevronRight, Activity, Clock, ArrowUpRight, RefreshCw, Send,
  Settings, Sparkles, Hash, Gauge, Zap, Bell, Tag, Command
} from 'lucide-react';
import { useApp } from '../context/AppContext';
import { formatDate, guildIconUrl } from '../utils/formatters';
import { StatCard } from '../components/shared/StatCard';

export function Dashboard() {
  const { guildInfo, guilds, currentGuildId, overview, activity, logs, setSection } = useApp();
  const selectedGuild = guilds.find((g) => g.id === currentGuildId);
  const moduleFlags = guildInfo?.modules || {};

  const quickActions = [
    { key: 'tickets', label: 'Ticket Panel senden', icon: <Send size={16} />, color: 'primary' as const },
    { key: 'serverstats', label: 'Sync starten', icon: <RefreshCw size={16} />, color: 'success' as const },
    { key: 'modules', label: 'Module aktualisieren', icon: <Zap size={16} />, color: 'warning' as const },
    { key: 'settings', label: 'Einstellungen oeffnen', icon: <Settings size={16} />, color: 'default' as const },
  ];

  return (
    <div className="space-y-6">
      <Card>
        <CardContent className="flex flex-col gap-6 xl:flex-row xl:items-center xl:justify-between">
          <div className="flex min-w-0 items-center gap-5">
            <Avatar className="size-20 shrink-0" radius="lg" src={guildIconUrl(selectedGuild)} />
            <div className="min-w-0">
              <div className="flex items-center gap-3">
                <h1 className="truncate text-3xl font-black tracking-tight">{guildInfo?.name || selectedGuild?.name}</h1>
                <Chip color="success" radius="sm" size="sm" startContent={<Bot size={12} />} variant="dot">
                  Online
                </Chip>
              </div>
              <div className="mt-1 text-small text-default-400">ID: {guildInfo?.id || selectedGuild?.id}</div>
              <div className="mt-3 flex flex-wrap gap-2">
                {Object.entries(moduleFlags).filter(([, v]) => v).map(([key]) => (
                  <Chip key={key} color="primary" size="sm" variant="flat">
                    {key.replace('Enabled', '').replace(/([A-Z])/g, ' $1').trim()}
                  </Chip>
                ))}
              </div>
            </div>
          </div>
          <div className="flex gap-2 shrink-0">
            <Chip color="primary" radius="sm" size="sm" variant="flat" startContent={<Gauge size={12} />}>
              Ping: {guildInfo?.ping || '-'}ms
            </Chip>
          </div>
        </CardContent>
      </Card>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
        <StatCard icon={<Users size={18} />} label="Mitglieder" value={guildInfo?.memberCount ?? 0} />
        <StatCard icon={<Activity size={18} />} label="Online" value={guildInfo?.onlineCount ?? '-'} />
        <StatCard icon={<Hash size={18} />} label="Channels" value={`${guildInfo?.textCount || 0}`} />
        <StatCard icon={<Shield size={18} />} label="Rollen" value={guildInfo?.roleCount ?? '-'} />
        <StatCard icon={<ArrowUpRight size={18} />} label="Boost Level" value={guildInfo?.boostLevel ?? '-'} />
        <StatCard icon={<Ticket size={18} />} label="Offene Tickets" value={overview?.tickets?.open ?? 0} color="warning" />
        <StatCard icon={<Command size={18} />} label="Commands (24h)" value={activity?.commands24h ?? 0} />
        <StatCard icon={<MessageSquare size={18} />} label="Nachrichten (24h)" value={activity?.messages24h ?? 0} />
        <StatCard icon={<Bot size={18} />} label="Automod (24h)" value={activity?.automod24h ?? 0} color="danger" />
        <StatCard icon={<Clock size={18} />} label="Uptime" value={guildInfo?.uptime || '-'} />
      </div>

      <div className="grid gap-5 xl:grid-cols-2 2xl:grid-cols-3">
        <Card>
          <CardHeader>
            <div>
              <h2 className="text-lg font-bold">Activity Bereich</h2>
              <p className="mt-0.5 text-tiny text-default-400">Live Statistiken</p>
            </div>
          </CardHeader>
          <CardContent className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            <StatCard icon={<MessageSquare size={16} />} label="Nachrichten" value={activity?.messages24h ?? 0} />
            <StatCard icon={<Command size={16} />} label="Commands" value={activity?.commands24h ?? 0} color="success" />
            <StatCard icon={<Shield size={16} />} label="Automod" value={activity?.automod24h ?? 0} color="warning" />
            <StatCard icon={<Users size={16} />} label="Neue User" value={activity?.newUsers24h ?? 0} />
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex items-center justify-between">
            <div>
              <h2 className="text-lg font-bold">Guild Logs</h2>
              <p className="mt-0.5 text-tiny text-default-400">Letzte Ereignisse</p>
            </div>
            <Button size="sm" variant="light" endContent={<ChevronRight size={14} />} onPress={() => setSection('settings')}>
              Alle
            </Button>
          </CardHeader>
          <CardContent>
            <ScrollShadow className="max-h-[320px] space-y-2 pr-1" hideScrollBar>
              {logs.length ? logs.slice(0, 15).map((log, i) => (
                <Card key={`${log.timestamp}-${i}`}>
                  <CardContent className="flex items-start gap-3 p-3">
                    <div className={`mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-lg ${
                      log.level === 'error' ? 'bg-danger-500/10 text-danger-400' :
                      log.level === 'warn' ? 'bg-warning-500/10 text-warning-400' :
                      'bg-primary-500/10 text-primary-400'
                    }`}>
                      {log.level === 'error' ? <Shield size={12} /> :
                       log.level === 'warn' ? <Bell size={12} /> :
                       <Activity size={12} />}
                    </div>
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <Chip
                          color={log.level === 'error' ? 'danger' : log.level === 'warn' ? 'warning' : 'default'}
                          size="sm"
                          variant="flat"
                        >
                          {(log.level || 'info').toUpperCase()}
                        </Chip>
                        <span className="text-tiny text-default-400">{formatDate(log.timestamp)}</span>
                      </div>
                      <p className="mt-1 text-small text-foreground/80">
                        {log.category ? <span className="text-default-500">[{log.category}] </span> : ''}{log.message || '-'}
                      </p>
                    </div>
                  </CardContent>
                </Card>
              )) : (
                <div className="flex flex-col items-center gap-2 py-6 text-center text-small text-default-400">
                  <Activity size={20} />
                  Keine Logs
                </div>
              )}
            </ScrollShadow>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <h2 className="text-lg font-bold">Quick Actions</h2>
            <p className="mt-0.5 text-tiny text-default-400">Schnellzugriff</p>
          </CardHeader>
          <CardContent className="flex flex-col gap-2">
            {quickActions.map((action) => (
              <Button
                key={action.key}
                className="justify-start"
                color={action.color}
                startContent={action.icon}
                variant="flat"
                onPress={() => setSection(action.key as any)}
              >
                {action.label}
              </Button>
            ))}
          </CardContent>
        </Card>
      </div>

      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
        {(['tickets', 'supportlogin', 'automod', 'welcome', 'birthday', 'reactionroles'] as const).map((key) => {
          const item = navItemMap[key];
          return (
            <Card key={key} isPressable onPress={() => setSection(key)}>
              <CardContent className="flex flex-col items-start gap-2">
                <Chip color="primary" size="sm" variant="flat" startContent={item.icon}>
                  {item.label}
                </Chip>
                <div className="font-semibold text-sm">{item.label}</div>
                <div className="text-tiny text-default-400">Modul verwalten</div>
              </CardContent>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

const navItemMap: Record<string, { label: string; icon: React.ReactNode }> = {
  tickets: { label: 'Ticketsystem', icon: <Ticket size={18} /> },
  supportlogin: { label: 'Support Login', icon: <Send size={18} /> },
  automod: { label: 'Automod', icon: <Shield size={18} /> },
  welcome: { label: 'Willkommen', icon: <Sparkles size={18} /> },
  birthday: { label: 'Birthday', icon: <CalendarDays size={18} /> },
  reactionroles: { label: 'Reaction Roles', icon: <Tag size={18} /> },
};
