import { useState } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { ArrowLeft, Save } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Button, Card, CardContent, Input, Label, Select } from '../../components/ui/primitives';
import type { Provider, Feed } from './types';

export function FeedNew() {
  const navigate = useNavigate();
  const [form, setForm] = useState({
    provider_id: 0,
    name: '',
    slug: '',
    feed_url: '',
    sync_frequency_hours: 24,
    is_active: true,
  });

  const { data: providers } = useQuery({
    queryKey: ['providers'],
    queryFn: () => api.get<{ providers: Provider[] }>('/providers'),
  });

  const createMut = useMutation({
    mutationFn: (body: typeof form) => api.post<{ feed: Feed }>('/feeds', body),
    onSuccess: (res) => {
      toast.success('Feed aangemaakt');
      navigate(`/cms/feeds/${res.feed.id}`);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.provider_id || !form.name || !form.feed_url) {
      toast.error('Provider, naam en URL zijn verplicht');
      return;
    }
    const slug = form.slug || form.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
    createMut.mutate({ ...form, slug });
  }

  return (
    <AppShell>
      <PageHeader
        title="Nieuwe feed"
        description="Configureer een affiliate-feed die product-data levert."
        actions={
          <Button variant="ghost" size="sm" onClick={() => navigate('/cms/feeds')}>
            <ArrowLeft className="h-4 w-4" />
            Terug
          </Button>
        }
      />
      <PageBody>
        <Card className="max-w-2xl">
          <CardContent>
            <form onSubmit={submit} className="space-y-4">
              <div>
                <Label htmlFor="provider">Provider</Label>
                <Select
                  id="provider"
                  className="mt-1"
                  value={form.provider_id}
                  onChange={(e) => setForm({ ...form, provider_id: Number(e.target.value) })}
                >
                  <option value={0}>— Kies provider —</option>
                  {providers?.providers?.map((p) => (
                    <option key={p.id} value={p.id}>
                      {p.name} ({p.adapter_type})
                    </option>
                  ))}
                </Select>
              </div>

              <div>
                <Label htmlFor="name">Naam</Label>
                <Input
                  id="name"
                  className="mt-1"
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  placeholder="bv. Nike.com via AWIN"
                  required
                />
              </div>

              <div>
                <Label htmlFor="slug">Slug (optioneel)</Label>
                <Input
                  id="slug"
                  className="mt-1"
                  value={form.slug}
                  onChange={(e) => setForm({ ...form, slug: e.target.value })}
                  placeholder="auto-gegenereerd uit naam"
                />
              </div>

              <div>
                <Label htmlFor="url">Feed URL</Label>
                <Input
                  id="url"
                  type="url"
                  className="mt-1"
                  value={form.feed_url}
                  onChange={(e) => setForm({ ...form, feed_url: e.target.value })}
                  placeholder="https://..."
                  required
                />
              </div>

              <div>
                <Label htmlFor="freq">Sync-frequentie (uren)</Label>
                <Input
                  id="freq"
                  type="number"
                  min={1}
                  max={168}
                  className="mt-1 w-32"
                  value={form.sync_frequency_hours}
                  onChange={(e) => setForm({ ...form, sync_frequency_hours: Number(e.target.value) })}
                />
              </div>

              <label className="flex items-center gap-2 cursor-pointer pt-2">
                <input
                  type="checkbox"
                  checked={form.is_active}
                  onChange={(e) => setForm({ ...form, is_active: e.target.checked })}
                  className="h-4 w-4 rounded border-[#333] bg-[#0A0A0A] text-[#00FF6A]"
                />
                <span className="text-sm text-[#F5F5F5]">Actief (sync automatisch)</span>
              </label>

              <div className="flex gap-2 pt-4 border-t border-[#333]">
                <Button type="submit" disabled={createMut.isPending}>
                  <Save className="h-4 w-4" />
                  {createMut.isPending ? 'Bezig...' : 'Feed aanmaken'}
                </Button>
                <Button type="button" variant="ghost" onClick={() => navigate('/cms/feeds')}>
                  Annuleren
                </Button>
              </div>
            </form>
          </CardContent>
        </Card>
      </PageBody>
    </AppShell>
  );
}
