'use client';

import type { GiveawayDashboard } from '@nexumi/shared';
import { Pause, Play, Plus, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { FieldAnchor } from '@/components/layout/field-anchor';
import { useTranslations } from '@/components/locale-provider';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { DiscordChannelSelect } from '@/components/ui/discord-channel-select';
import { DiscordRoleSelect } from '@/components/ui/discord-role-select';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

const EMPTY_DRAFT = {
  channelId: '',
  prize: '',
  winnerCount: '1',
  endsAt: '',
  requiredRoleId: '',
  requiredLevel: '',
  requiredMemberDays: ''
};

function formatDate(iso: string): string {
  return new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' });
}

interface GiveawaysManagerProps {
  guildId: string;
  initialGiveaways: GiveawayDashboard[];
}

export function GiveawaysManager({ guildId, initialGiveaways }: GiveawaysManagerProps) {
  const t = useTranslations();
  const [giveaways, setGiveaways] = useState<GiveawayDashboard[]>(initialGiveaways);
  const [draft, setDraft] = useState(EMPTY_DRAFT);
  const [creating, setCreating] = useState(false);
  const [pendingId, setPendingId] = useState<string | null>(null);

  async function handleCreate() {
    if (!draft.channelId.trim() || !draft.prize.trim() || !draft.endsAt) {
      toast.error(t('modulePages.giveaways.formIncomplete'));
      return;
    }
    setCreating(true);
    try {
      const response = await fetch(`/api/guilds/${guildId}/giveaways`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          channelId: draft.channelId.trim(),
          prize: draft.prize.trim(),
          winnerCount: Number(draft.winnerCount) || 1,
          endsAt: new Date(draft.endsAt).toISOString(),
          requiredRoleId: draft.requiredRoleId.trim() || undefined,
          requiredLevel: draft.requiredLevel.trim() ? Number(draft.requiredLevel) : undefined,
          requiredMemberDays: draft.requiredMemberDays.trim() ? Number(draft.requiredMemberDays) : undefined
        })
      });
      const body = (await response.json().catch(() => null)) as (GiveawayDashboard & { error?: string }) | null;
      if (!response.ok || !body) {
        toast.error(body?.error ?? t('common.saveError'));
        return;
      }
      setGiveaways((prev) => [body, ...prev]);
      setDraft(EMPTY_DRAFT);
      toast.success(t('modulePages.giveaways.created'));
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setCreating(false);
    }
  }

  async function handleAction(giveaway: GiveawayDashboard, action: 'end' | 'pause' | 'unpause') {
    setPendingId(giveaway.id);
    try {
      const response = await fetch(`/api/guilds/${guildId}/giveaways/${giveaway.id}/action`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action })
      });
      const body = (await response.json().catch(() => null)) as
        | (GiveawayDashboard & { error?: string })
        | { error?: string }
        | null;
      if (!response.ok || !body || !('id' in body)) {
        toast.error(
          (body && 'error' in body && body.error) || t('common.saveError')
        );
        return;
      }
      if (action === 'end' && !body.endedAt) {
        toast.error(t('common.saveError'));
        return;
      }
      setGiveaways((prev) => prev.map((entry) => (entry.id === giveaway.id ? body : entry)));
      toast.success(t('common.saveSuccess'));
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setPendingId(null);
    }
  }

  async function handleDelete(giveaway: GiveawayDashboard) {
    if (!window.confirm(t('modulePages.giveaways.confirmDelete'))) {
      return;
    }
    setPendingId(giveaway.id);
    try {
      const response = await fetch(`/api/guilds/${guildId}/giveaways/${giveaway.id}`, { method: 'DELETE' });
      if (!response.ok) {
        toast.error(t('common.saveError'));
        return;
      }
      setGiveaways((prev) => prev.filter((entry) => entry.id !== giveaway.id));
      toast.success(t('common.saveSuccess'));
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setPendingId(null);
    }
  }

  return (
    <div className="space-y-6">
      <FieldAnchor id="field-giveaways-create">
      <Card>
        <CardHeader>
          <CardTitle>{t('modulePages.giveaways.createTitle')}</CardTitle>
          <CardDescription>{t('modulePages.giveaways.createDescription')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label>{t('modulePages.giveaways.channelId')}</Label>
              <DiscordChannelSelect
                guildId={guildId}
                value={draft.channelId}
                onChange={(channelId) => setDraft((prev) => ({ ...prev, channelId }))}
              />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.giveaways.prize')}</Label>
              <Input value={draft.prize} onChange={(event) => setDraft((prev) => ({ ...prev, prize: event.target.value }))} />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.giveaways.winnerCount')}</Label>
              <Input
                type="number"
                min={1}
                value={draft.winnerCount}
                onChange={(event) => setDraft((prev) => ({ ...prev, winnerCount: event.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.giveaways.endsAt')}</Label>
              <Input
                type="datetime-local"
                value={draft.endsAt}
                onChange={(event) => setDraft((prev) => ({ ...prev, endsAt: event.target.value }))}
              />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.giveaways.requiredRoleId')}</Label>
              <DiscordRoleSelect
                guildId={guildId}
                value={draft.requiredRoleId}
                onChange={(requiredRoleId) => setDraft((prev) => ({ ...prev, requiredRoleId }))}
                placeholder={t('common.optional')}
              />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.giveaways.requiredLevel')}</Label>
              <Input
                type="number"
                min={0}
                value={draft.requiredLevel}
                onChange={(event) => setDraft((prev) => ({ ...prev, requiredLevel: event.target.value }))}
                placeholder={t('common.optional')}
              />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.giveaways.requiredMemberDays')}</Label>
              <Input
                type="number"
                min={0}
                value={draft.requiredMemberDays}
                onChange={(event) => setDraft((prev) => ({ ...prev, requiredMemberDays: event.target.value }))}
                placeholder={t('common.optional')}
              />
            </div>
          </div>
          <Button type="button" onClick={handleCreate} disabled={creating}>
            <Plus className="size-4" />
            {creating ? t('common.saving') : t('modulePages.giveaways.create')}
          </Button>
        </CardContent>
      </Card>
      </FieldAnchor>

      <FieldAnchor id="field-giveaways-list">

      <Card>
        <CardHeader>
          <CardTitle>{t('modulePages.giveaways.listTitle')}</CardTitle>
          <CardDescription>{t('modulePages.giveaways.listDescription')}</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {giveaways.length === 0 && (
            <p className="text-sm text-muted-foreground">{t('modulePages.giveaways.empty')}</p>
          )}
          {giveaways.map((giveaway) => {
            const ended = Boolean(giveaway.endedAt);
            return (
              <div key={giveaway.id} className="space-y-3 rounded-md border border-border p-4">
                <div className="flex flex-wrap items-start justify-between gap-2">
                  <div>
                    <p className="font-medium">{giveaway.prize}</p>
                    <p className="text-xs text-muted-foreground">
                      #{giveaway.channelId} · {t('modulePages.giveaways.winnerCount')}: {giveaway.winnerCount} ·{' '}
                      {t('modulePages.giveaways.entrants')}: {giveaway.entrants.length}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    {ended ? (
                      <Badge variant="secondary">{t('modulePages.giveaways.statusEnded')}</Badge>
                    ) : giveaway.paused ? (
                      <Badge variant="secondary">{t('modulePages.giveaways.statusPaused')}</Badge>
                    ) : (
                      <Badge variant="success">{t('modulePages.giveaways.statusActive')}</Badge>
                    )}
                  </div>
                </div>
                <p className="text-xs text-muted-foreground">
                  {ended
                    ? `${t('modulePages.giveaways.endedAt')}: ${formatDate(giveaway.endedAt!)}`
                    : `${t('modulePages.giveaways.endsAt')}: ${formatDate(giveaway.endsAt)}`}
                </p>
                {ended && giveaway.winners.length > 0 && (
                  <p className="text-xs text-muted-foreground">
                    {t('modulePages.giveaways.winners')}: {giveaway.winners.map((id) => `<@${id}>`).join(', ')}
                  </p>
                )}
                {!ended && (
                  <div className="flex flex-wrap gap-2">
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      disabled={pendingId === giveaway.id}
                      onClick={() => handleAction(giveaway, giveaway.paused ? 'unpause' : 'pause')}
                    >
                      {giveaway.paused ? <Play className="size-4" /> : <Pause className="size-4" />}
                      {giveaway.paused ? t('modulePages.giveaways.unpause') : t('modulePages.giveaways.pause')}
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="outline"
                      disabled={pendingId === giveaway.id}
                      onClick={() => handleAction(giveaway, 'end')}
                    >
                      {t('modulePages.giveaways.end')}
                    </Button>
                    <Button
                      type="button"
                      size="sm"
                      variant="ghost"
                      disabled={pendingId === giveaway.id}
                      onClick={() => handleDelete(giveaway)}
                    >
                      <Trash2 className="size-4" />
                      {t('common.remove')}
                    </Button>
                  </div>
                )}
                {ended && (
                  <div>
                    <Button
                      type="button"
                      size="sm"
                      variant="ghost"
                      disabled={pendingId === giveaway.id}
                      onClick={() => handleDelete(giveaway)}
                    >
                      <Trash2 className="size-4" />
                      {t('common.remove')}
                    </Button>
                  </div>
                )}
              </div>
            );
          })}
        </CardContent>
      </Card>
      </FieldAnchor>
    </div>
  );
}
