'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useMemo, useState, useTransition } from 'react';
import { toast } from 'sonner';
import type { OwnerGuildListItem, OwnerRole } from '@nexumi/shared';
import { useTranslations } from '@/components/locale-provider';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';

async function readError(response: Response): Promise<string> {
  const data = (await response.json().catch(() => null)) as { error?: string } | null;
  return data?.error ?? 'Request failed';
}

export function UsersManager({
  initialUsers
}: {
  initialUsers: Array<{ id: string; userId: string; reason: string | null; note: string | null }>;
}) {
  const t = useTranslations();
  const router = useRouter();
  const [userId, setUserId] = useState('');
  const [reason, setReason] = useState('');
  const [pending, startTransition] = useTransition();

  return (
    <div className="space-y-4">
      <Card>
        <CardContent className="space-y-3 pt-6">
          <Input placeholder={t('owner.users.userIdPlaceholder')} value={userId} onChange={(e) => setUserId(e.target.value)} />
          <Input placeholder={t('owner.common.noteOptional')} value={reason} onChange={(e) => setReason(e.target.value)} />
          <Button
            disabled={pending || !userId.trim()}
            onClick={() =>
              startTransition(async () => {
                const response = await fetch('/api/owner/users', {
                  method: 'PUT',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({ userId: userId.trim(), reason: reason.trim() || null })
                });
                if (!response.ok) {
                  toast.error(await readError(response));
                  return;
                }
                setUserId('');
                setReason('');
                toast.success(t('common.saveSuccess'));
                router.refresh();
              })
            }
          >
            {t('common.add')}
          </Button>
        </CardContent>
      </Card>
      <Card>
        <CardContent className="divide-y divide-border p-0">
          {initialUsers.length === 0 ? (
            <p className="p-4 text-sm text-muted-foreground">{t('owner.common.empty')}</p>
          ) : (
            initialUsers.map((user) => (
              <div key={user.id} className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
                <div>
                  <p className="font-medium">{user.userId}</p>
                  {(user.reason || user.note) && (
                    <p className="text-muted-foreground">{user.reason ?? user.note}</p>
                  )}
                </div>
                <Button
                  variant="destructive"
                  size="sm"
                  disabled={pending}
                  onClick={() =>
                    startTransition(async () => {
                      const response = await fetch(`/api/owner/users?userId=${user.userId}`, { method: 'DELETE' });
                      if (!response.ok) {
                        toast.error(await readError(response));
                        return;
                      }
                      toast.success(t('common.saveSuccess'));
                      router.refresh();
                    })
                  }
                >
                  {t('common.remove')}
                </Button>
              </div>
            ))
          )}
        </CardContent>
      </Card>
    </div>
  );
}

export function GuildsManager({
  initialGuilds
}: {
  initialGuilds: OwnerGuildListItem[];
}) {
  const t = useTranslations();
  const router = useRouter();
  const [query, setQuery] = useState('');
  const [pending, startTransition] = useTransition();
  const filtered = useMemo(() => {
    const needle = query.trim().toLowerCase();
    if (!needle) {
      return initialGuilds;
    }
    return initialGuilds.filter(
      (guild) =>
        guild.id.includes(needle) ||
        (guild.name?.toLowerCase().includes(needle) ?? false)
    );
  }, [initialGuilds, query]);

  async function postAction(action: string, guildId: string, reason?: string) {
    const response = await fetch('/api/owner/guilds', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action, guildId, reason })
    });
    if (!response.ok) {
      throw new Error(await readError(response));
    }
    return (await response.json()) as { ok?: boolean; url?: string };
  }

  return (
    <div className="space-y-4">
      <Input placeholder={t('owner.guilds.search')} value={query} onChange={(e) => setQuery(e.target.value)} />
      <Card>
        <CardContent className="divide-y divide-border p-0">
          {filtered.length === 0 ? (
            <p className="p-4 text-sm text-muted-foreground">{t('owner.common.empty')}</p>
          ) : (
            filtered.map((guild) => {
              const displayName = guild.name ?? t('owner.guilds.unknownName');
              const initials = displayName.slice(0, 2).toUpperCase();
              return (
                <div
                  key={guild.id}
                  className="flex flex-col gap-3 px-4 py-3 text-sm sm:flex-row sm:items-center sm:justify-between"
                >
                  <div className="flex min-w-0 items-center gap-3">
                    <Avatar className="h-10 w-10 shrink-0">
                      {guild.iconUrl ? <AvatarImage src={guild.iconUrl} alt="" /> : null}
                      <AvatarFallback>{initials}</AvatarFallback>
                    </Avatar>
                    <div className="min-w-0">
                      <p className="truncate font-medium">{displayName}</p>
                      <p className="truncate text-muted-foreground">
                        <span className="font-mono text-xs">{guild.id}</span>
                        {' · '}
                        {guild.memberCount != null
                          ? t('owner.guilds.members', { count: String(guild.memberCount) })
                          : t('owner.guilds.membersUnknown')}
                        {' · '}
                        {guild.locale} · {new Date(guild.createdAt).toLocaleDateString()}
                        {guild.blacklisted ? ` · ${t('owner.guilds.blacklisted')}` : ''}
                      </p>
                    </div>
                  </div>
                  <div className="flex flex-wrap gap-2">
                    <Button size="sm" variant="default" asChild>
                      <Link href={`/dashboard/${guild.id}`}>{t('owner.guilds.openDashboard')}</Link>
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      disabled={pending}
                      onClick={() =>
                        startTransition(async () => {
                          try {
                            const result = await postAction('createInvite', guild.id);
                            if (result.url) {
                              try {
                                await navigator.clipboard.writeText(result.url);
                                toast.success(t('owner.guilds.inviteCopied', { url: result.url }));
                              } catch {
                                toast.success(t('owner.guilds.inviteCreated', { url: result.url }));
                              }
                            } else {
                              toast.success(t('common.saveSuccess'));
                            }
                          } catch (error) {
                            toast.error(error instanceof Error ? error.message : t('common.saveError'));
                          }
                        })
                      }
                    >
                      {t('owner.guilds.createInvite')}
                    </Button>
                    <Button
                      size="sm"
                      variant="secondary"
                      disabled={pending}
                      onClick={() =>
                        startTransition(async () => {
                          try {
                            await postAction(guild.blacklisted ? 'unblacklist' : 'blacklist', guild.id, 'Owner panel');
                            toast.success(t('common.saveSuccess'));
                            router.refresh();
                          } catch (error) {
                            toast.error(error instanceof Error ? error.message : t('common.saveError'));
                          }
                        })
                      }
                    >
                      {guild.blacklisted ? t('owner.guilds.unblacklist') : t('owner.guilds.blacklist')}
                    </Button>
                    <Button
                      size="sm"
                      variant="destructive"
                      disabled={pending}
                      onClick={() =>
                        startTransition(async () => {
                          if (!window.confirm(t('owner.guilds.leaveConfirm'))) {
                            return;
                          }
                          try {
                            await postAction('leave', guild.id);
                            toast.success(t('common.saveSuccess'));
                            router.refresh();
                          } catch (error) {
                            toast.error(error instanceof Error ? error.message : t('common.saveError'));
                          }
                        })
                      }
                    >
                      {t('owner.guilds.leave')}
                    </Button>
                  </div>
                </div>
              );
            })
          )}
        </CardContent>
      </Card>
    </div>
  );
}

export function FlagsManager({
  initialFlags
}: {
  initialFlags: Array<{
    id: string;
    key: string;
    enabled: boolean;
    rolloutPercent: number;
    whitelistGuildIds: string[];
  }>;
}) {
  const t = useTranslations();
  const router = useRouter();
  const [key, setKey] = useState('');
  const [rollout, setRollout] = useState('0');
  const [pending, startTransition] = useTransition();

  return (
    <div className="space-y-4">
      <Card>
        <CardContent className="grid gap-3 pt-6 sm:grid-cols-3">
          <Input placeholder={t('owner.flags.keyPlaceholder')} value={key} onChange={(e) => setKey(e.target.value)} />
          <Input
            type="number"
            min={0}
            max={100}
            value={rollout}
            onChange={(e) => setRollout(e.target.value)}
            placeholder={t('owner.flags.rollout')}
          />
          <Button
            disabled={pending || !key.trim()}
            onClick={() =>
              startTransition(async () => {
                const response = await fetch('/api/owner/flags', {
                  method: 'PUT',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({
                    key: key.trim(),
                    enabled: true,
                    rolloutPercent: Number(rollout) || 0,
                    whitelistGuildIds: []
                  })
                });
                if (!response.ok) {
                  toast.error(await readError(response));
                  return;
                }
                setKey('');
                toast.success(t('common.saveSuccess'));
                router.refresh();
              })
            }
          >
            {t('common.add')}
          </Button>
        </CardContent>
      </Card>
      <Card>
        <CardContent className="divide-y divide-border p-0">
          {initialFlags.map((flag) => (
            <div key={flag.id} className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
              <div>
                <p className="font-medium">{flag.key}</p>
                <p className="text-muted-foreground">
                  {flag.enabled ? t('common.enabled') : t('common.disabled')} · {flag.rolloutPercent}%
                </p>
              </div>
              <div className="flex gap-2">
                <Button
                  size="sm"
                  variant="secondary"
                  disabled={pending}
                  onClick={() =>
                    startTransition(async () => {
                      const response = await fetch('/api/owner/flags', {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                          key: flag.key,
                          enabled: !flag.enabled,
                          rolloutPercent: flag.rolloutPercent,
                          whitelistGuildIds: flag.whitelistGuildIds
                        })
                      });
                      if (!response.ok) {
                        toast.error(await readError(response));
                        return;
                      }
                      router.refresh();
                    })
                  }
                >
                  {flag.enabled ? t('common.disabled') : t('common.enabled')}
                </Button>
                <Button
                  size="sm"
                  variant="destructive"
                  disabled={pending}
                  onClick={() =>
                    startTransition(async () => {
                      const response = await fetch(`/api/owner/flags?key=${encodeURIComponent(flag.key)}`, {
                        method: 'DELETE'
                      });
                      if (!response.ok) {
                        toast.error(await readError(response));
                        return;
                      }
                      router.refresh();
                    })
                  }
                >
                  {t('common.remove')}
                </Button>
              </div>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}

export function TeamManager({
  bootstrapOwnerIds,
  initialMembers
}: {
  bootstrapOwnerIds: string[];
  initialMembers: Array<{ id: string; userId: string; role: string; note: string | null }>;
}) {
  const t = useTranslations();
  const router = useRouter();
  const [userId, setUserId] = useState('');
  const [role, setRole] = useState<OwnerRole>('SUPPORT');
  const [pending, startTransition] = useTransition();

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t('owner.team.bootstrap')}</CardTitle>
        </CardHeader>
        <CardContent className="text-sm text-muted-foreground">
          {bootstrapOwnerIds.length === 0
            ? t('owner.team.noBootstrap')
            : bootstrapOwnerIds.join(', ')}
        </CardContent>
      </Card>
      <Card>
        <CardContent className="grid gap-3 pt-6 sm:grid-cols-3">
          <Input placeholder={t('owner.users.userIdPlaceholder')} value={userId} onChange={(e) => setUserId(e.target.value)} />
          <select
            className="flex h-10 rounded-md border border-input bg-background px-3 text-sm"
            value={role}
            onChange={(e) => setRole(e.target.value as OwnerRole)}
          >
            {(['VIEWER', 'SUPPORT', 'ADMIN', 'OWNER'] as OwnerRole[]).map((item) => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>
          <Button
            disabled={pending || !userId.trim()}
            onClick={() =>
              startTransition(async () => {
                const response = await fetch('/api/owner/team', {
                  method: 'PUT',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({ userId: userId.trim(), role, note: null })
                });
                if (!response.ok) {
                  toast.error(await readError(response));
                  return;
                }
                setUserId('');
                toast.success(t('common.saveSuccess'));
                router.refresh();
              })
            }
          >
            {t('common.add')}
          </Button>
        </CardContent>
      </Card>
      <Card>
        <CardContent className="divide-y divide-border p-0">
          {initialMembers.map((member) => (
            <div key={member.id} className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
              <div>
                <p className="font-medium">{member.userId}</p>
                <p className="text-muted-foreground">{member.role}</p>
              </div>
              <Button
                size="sm"
                variant="destructive"
                disabled={pending}
                onClick={() =>
                  startTransition(async () => {
                    const response = await fetch(`/api/owner/team?userId=${member.userId}`, { method: 'DELETE' });
                    if (!response.ok) {
                      toast.error(await readError(response));
                      return;
                    }
                    router.refresh();
                  })
                }
              >
                {t('common.remove')}
              </Button>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}

export function JobsManager({
  initialQueues,
  initialMigrations
}: {
  initialQueues: Array<{
    name: string;
    waiting: number;
    active: number;
    completed: number;
    failed: number;
    delayed: number;
  }>;
  initialMigrations: Array<{ name: string; finishedAt: string | null }>;
}) {
  const t = useTranslations();
  const router = useRouter();
  const [pending, startTransition] = useTransition();

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t('owner.jobs.queues')}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          {initialQueues.map((queue) => (
            <div key={queue.name} className="flex flex-col gap-2 border-b border-border/60 py-3 text-sm last:border-0 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <p className="font-medium">{queue.name}</p>
                <p className="text-muted-foreground">
                  wait {queue.waiting} · active {queue.active} · failed {queue.failed} · delayed {queue.delayed}
                </p>
              </div>
              <Button
                size="sm"
                variant="secondary"
                disabled={pending || queue.failed === 0}
                onClick={() =>
                  startTransition(async () => {
                    const response = await fetch('/api/owner/jobs', {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify({ queueName: queue.name })
                    });
                    if (!response.ok) {
                      toast.error(await readError(response));
                      return;
                    }
                    toast.success(t('common.saveSuccess'));
                    router.refresh();
                  })
                }
              >
                {t('owner.jobs.retryFailed')}
              </Button>
            </div>
          ))}
        </CardContent>
      </Card>
      <Card>
        <CardHeader>
          <CardTitle className="text-base">{t('owner.jobs.migrations')}</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2 text-sm">
          {initialMigrations.map((migration) => (
            <div key={migration.name} className="flex justify-between gap-2">
              <span>{migration.name}</span>
              <span className="text-muted-foreground">
                {migration.finishedAt ? new Date(migration.finishedAt).toLocaleString() : '—'}
              </span>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}

export function ChangelogManager({
  initialEntries
}: {
  initialEntries: Array<{ id: string; version: string; title: string; body: string; publishedAt: string }>;
}) {
  const t = useTranslations();
  const router = useRouter();
  const [version, setVersion] = useState('');
  const [title, setTitle] = useState('');
  const [body, setBody] = useState('');
  const [pending, startTransition] = useTransition();

  return (
    <div className="space-y-4">
      <Card>
        <CardContent className="space-y-3 pt-6">
          <Input placeholder={t('owner.changelog.version')} value={version} onChange={(e) => setVersion(e.target.value)} />
          <Input placeholder={t('owner.changelog.titleField')} value={title} onChange={(e) => setTitle(e.target.value)} />
          <textarea
            className="min-h-28 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
            placeholder={t('owner.changelog.body')}
            value={body}
            onChange={(e) => setBody(e.target.value)}
          />
          <Button
            disabled={pending || !version.trim() || !title.trim() || !body.trim()}
            onClick={() =>
              startTransition(async () => {
                const response = await fetch('/api/owner/changelog', {
                  method: 'POST',
                  headers: { 'Content-Type': 'application/json' },
                  body: JSON.stringify({ version: version.trim(), title: title.trim(), body: body.trim() })
                });
                if (!response.ok) {
                  toast.error(await readError(response));
                  return;
                }
                setVersion('');
                setTitle('');
                setBody('');
                toast.success(t('common.saveSuccess'));
                router.refresh();
              })
            }
          >
            {t('common.add')}
          </Button>
        </CardContent>
      </Card>
      <Card>
        <CardContent className="divide-y divide-border p-0">
          {initialEntries.map((entry) => (
            <div key={entry.id} className="flex items-start justify-between gap-3 px-4 py-3 text-sm">
              <div>
                <p className="font-medium">
                  {entry.version} — {entry.title}
                </p>
                <p className="text-muted-foreground whitespace-pre-wrap">{entry.body}</p>
              </div>
              <Button
                size="sm"
                variant="destructive"
                disabled={pending}
                onClick={() =>
                  startTransition(async () => {
                    const response = await fetch(`/api/owner/changelog?id=${entry.id}`, { method: 'DELETE' });
                    if (!response.ok) {
                      toast.error(await readError(response));
                      return;
                    }
                    router.refresh();
                  })
                }
              >
                {t('common.remove')}
              </Button>
            </div>
          ))}
        </CardContent>
      </Card>
    </div>
  );
}
