'use client';

import type { SocialFeedDashboard } from '@nexumi/shared';
import { 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 { 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';
import { PlaceholderHelp } from '@/components/ui/placeholder-help';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';

const FEED_TYPES: SocialFeedDashboard['type'][] = ['TWITCH', 'YOUTUBE', 'RSS', 'REDDIT'];

interface LocalFeed extends SocialFeedDashboard {
  clientKey: string;
  saving?: boolean;
}

const EMPTY_DRAFT = {
  type: 'RSS' as SocialFeedDashboard['type'],
  sourceId: '',
  channelId: '',
  rolePingId: '',
  template: ''
};

interface FeedsManagerProps {
  guildId: string;
  initialFeeds: SocialFeedDashboard[];
}

export function FeedsManager({ guildId, initialFeeds }: FeedsManagerProps) {
  const t = useTranslations();
  const [feeds, setFeeds] = useState<LocalFeed[]>(
    initialFeeds.map((feed, index) => ({ ...feed, clientKey: feed.id ?? `existing-${index}` }))
  );
  const [draft, setDraft] = useState(EMPTY_DRAFT);
  const [creating, setCreating] = useState(false);

  async function handleCreate() {
    if (!draft.sourceId.trim() || !draft.channelId.trim()) {
      toast.error(t('modulePages.feeds.formIncomplete'));
      return;
    }
    setCreating(true);
    try {
      const response = await fetch(`/api/guilds/${guildId}/feeds`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: draft.type,
          sourceId: draft.sourceId.trim(),
          channelId: draft.channelId.trim(),
          rolePingId: draft.rolePingId.trim() || undefined,
          template: draft.template.trim() || null,
          enabled: true
        })
      });
      const body = (await response.json().catch(() => null)) as (SocialFeedDashboard & { error?: string }) | null;
      if (!response.ok || !body) {
        toast.error(body?.error ?? t('common.saveError'));
        return;
      }
      setFeeds((prev) => [...prev, { ...body, clientKey: body.id ?? `new-${Date.now()}` }]);
      setDraft(EMPTY_DRAFT);
      toast.success(t('common.saveSuccess'));
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setCreating(false);
    }
  }

  async function handleToggle(feed: LocalFeed) {
    setFeeds((prev) => prev.map((entry) => (entry.clientKey === feed.clientKey ? { ...entry, saving: true } : entry)));
    try {
      const response = await fetch(`/api/guilds/${guildId}/feeds/${feed.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ enabled: !feed.enabled })
      });
      const body = (await response.json().catch(() => null)) as (SocialFeedDashboard & { error?: string }) | null;
      if (!response.ok || !body) {
        toast.error(body?.error ?? t('common.saveError'));
        return;
      }
      setFeeds((prev) =>
        prev.map((entry) => (entry.clientKey === feed.clientKey ? { ...body, clientKey: entry.clientKey } : entry))
      );
    } catch {
      toast.error(t('common.saveError'));
    } finally {
      setFeeds((prev) =>
        prev.map((entry) => (entry.clientKey === feed.clientKey ? { ...entry, saving: false } : entry))
      );
    }
  }

  async function handleDelete(feed: LocalFeed) {
    if (!window.confirm(t('modulePages.feeds.confirmDelete'))) {
      return;
    }
    try {
      const response = await fetch(`/api/guilds/${guildId}/feeds/${feed.id}`, { method: 'DELETE' });
      if (!response.ok) {
        toast.error(t('common.saveError'));
        return;
      }
      setFeeds((prev) => prev.filter((entry) => entry.clientKey !== feed.clientKey));
      toast.success(t('common.saveSuccess'));
    } catch {
      toast.error(t('common.saveError'));
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t('modulePages.feeds.title')}</CardTitle>
        <CardDescription>{t('modulePages.feeds.description')}</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {feeds.length === 0 && <p className="text-sm text-muted-foreground">{t('modulePages.feeds.empty')}</p>}
        {feeds.map((feed) => (
          <div key={feed.clientKey} 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">
                  {feed.type} · {feed.sourceId}
                </p>
                <p className="text-xs text-muted-foreground">
                  #{feed.channelId}
                  {feed.rolePingId ? ` · @${feed.rolePingId}` : ''}
                </p>
              </div>
              <div className="flex items-center gap-2">
                <Switch checked={feed.enabled} disabled={feed.saving} onCheckedChange={() => handleToggle(feed)} />
                <Button
                  type="button"
                  variant="ghost"
                  size="icon"
                  aria-label={t('common.remove')}
                  onClick={() => handleDelete(feed)}
                >
                  <Trash2 className="size-4" />
                </Button>
              </div>
            </div>
          </div>
        ))}

        <FieldAnchor id="field-feeds-add">
        <div className="space-y-3 rounded-md border border-dashed border-border p-4">
          <p className="text-sm font-medium">{t('modulePages.feeds.addFeed')}</p>
          <div className="grid gap-3 sm:grid-cols-2">
            <div className="space-y-2">
              <Label>{t('modulePages.feeds.type')}</Label>
              <Select value={draft.type} onValueChange={(type) => setDraft((prev) => ({ ...prev, type: type as SocialFeedDashboard['type'] }))}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {FEED_TYPES.map((type) => (
                    <SelectItem key={type} value={type}>
                      {type}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.feeds.sourceId')}</Label>
              <Input
                value={draft.sourceId}
                onChange={(event) => setDraft((prev) => ({ ...prev, sourceId: event.target.value }))}
                placeholder={t('modulePages.feeds.sourceIdPlaceholder')}
              />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.feeds.channelId')}</Label>
              <DiscordChannelSelect
                guildId={guildId}
                value={draft.channelId}
                onChange={(channelId) => setDraft((prev) => ({ ...prev, channelId }))}
              />
            </div>
            <div className="space-y-2">
              <Label>{t('modulePages.feeds.rolePingId')}</Label>
              <DiscordRoleSelect
                guildId={guildId}
                value={draft.rolePingId}
                onChange={(rolePingId) => setDraft((prev) => ({ ...prev, rolePingId }))}
                placeholder={t('common.optional')}
              />
            </div>
            <div className="col-span-2 space-y-2">
              <Label>{t('modulePages.feeds.template')}</Label>
              <Input
                value={draft.template}
                onChange={(event) => setDraft((prev) => ({ ...prev, template: event.target.value }))}
                placeholder={t('modulePages.feeds.templatePlaceholder')}
              />
              <PlaceholderHelp preset="feeds" />
            </div>
          </div>
          <Button type="button" variant="outline" onClick={handleCreate} disabled={creating}>
            <Plus className="size-4" />
            {t('modulePages.feeds.addFeed')}
          </Button>
        </div>
        </FieldAnchor>
      </CardContent>
    </Card>
  );
}
