'use client';

import { useRouter } from 'next/navigation';
import { useMemo, useState, useTransition } from 'react';
import { toast } from 'sonner';
import type { BotPresenceConfig, OwnerRole } from '@nexumi/shared';
import { useTranslations } from '@/components/locale-provider';
import { SettingsForm } from '@/components/settings/settings-form';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

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 PresenceForm({ initialValue }: { initialValue: BotPresenceConfig }) {
  const t = useTranslations();
  return (
    <SettingsForm
      initialValue={initialValue}
      onSave={async (value) => {
        const response = await fetch('/api/owner/presence', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(value)
        });
        if (!response.ok) {
          return { ok: false, error: await readError(response) };
        }
        return { ok: true };
      }}
    >
      {({ value, setValue, error }) => (
        <Card>
          <CardContent className="space-y-4 pt-6">
            {error && <p className="text-sm text-destructive">{error}</p>}
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>{t('owner.presence.status')}</Label>
                <select
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
                  value={value.status}
                  onChange={(e) => setValue({ ...value, status: e.target.value as BotPresenceConfig['status'] })}
                >
                  {['online', 'idle', 'dnd', 'invisible'].map((status) => (
                    <option key={status} value={status}>
                      {status}
                    </option>
                  ))}
                </select>
              </div>
              <div className="space-y-2">
                <Label>{t('owner.presence.activityType')}</Label>
                <select
                  className="flex h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
                  value={value.activityType}
                  onChange={(e) =>
                    setValue({ ...value, activityType: e.target.value as BotPresenceConfig['activityType'] })
                  }
                >
                  {['Playing', 'Listening', 'Watching', 'Competing'].map((type) => (
                    <option key={type} value={type}>
                      {type}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            <div className="space-y-2">
              <Label>{t('owner.presence.activityText')}</Label>
              <Input value={value.activityText} onChange={(e) => setValue({ ...value, activityText: e.target.value })} />
            </div>
            <div className="space-y-2">
              <Label>{t('owner.presence.rotating')}</Label>
              <textarea
                className="min-h-24 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                value={value.rotatingMessages.join('\n')}
                onChange={(e) =>
                  setValue({
                    ...value,
                    rotatingMessages: e.target.value
                      .split('\n')
                      .map((line) => line.trim())
                      .filter(Boolean)
                  })
                }
              />
            </div>
            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                checked={value.maintenanceMode}
                onChange={(e) => setValue({ ...value, maintenanceMode: e.target.checked })}
              />
              {t('owner.presence.maintenanceMode')}
            </label>
            <div className="space-y-2">
              <Label>{t('owner.presence.maintenanceMessage')}</Label>
              <Input
                value={value.maintenanceMessage ?? ''}
                onChange={(e) => setValue({ ...value, maintenanceMessage: e.target.value || null })}
              />
            </div>
          </CardContent>
        </Card>
      )}
    </SettingsForm>
  );
}

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: Array<{ id: string; locale: string; createdAt: string; blacklisted: boolean }>;
}) {
  const t = useTranslations();
  const router = useRouter();
  const [query, setQuery] = useState('');
  const [pending, startTransition] = useTransition();
  const filtered = useMemo(
    () => initialGuilds.filter((guild) => guild.id.includes(query.trim())),
    [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 (
    <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) => (
              <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>
                  <p className="font-medium">{guild.id}</p>
                  <p className="text-muted-foreground">
                    {guild.locale} · {new Date(guild.createdAt).toLocaleDateString()}
                    {guild.blacklisted ? ` · ${t('owner.guilds.blacklisted')}` : ''}
                  </p>
                </div>
                <div className="flex flex-wrap gap-2">
                  <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>
  );
}
