import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Link, useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { Plus, Trash2 } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Button, Badge, Card, Input, Label, Select } from '../../components/ui/primitives';
import { Table, THead, TBody, TR, TH, TD } from '../../components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '../../components/ui/dialog';

interface Collection {
  id: string;
  name: string;
  slug: string;
  type: 'smart' | 'manual';
  enabled: boolean;
  product_count: number;
  updated_at: string;
}

export function CollectionsList() {
  const qc = useQueryClient();
  const navigate = useNavigate();
  const [newOpen, setNewOpen] = useState(false);
  const [form, setForm] = useState({ name: '', slug: '', type: 'smart' as 'smart' | 'manual' });

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

  const createMut = useMutation({
    mutationFn: () => api.post<{ collection: Collection }>('/collections', form),
    onSuccess: (res) => {
      setNewOpen(false);
      setForm({ name: '', slug: '', type: 'smart' });
      navigate(`/cms/collections/${res.collection.id}`);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const deleteMut = useMutation({
    mutationFn: (id: string) => api.delete(`/collections/${id}`),
    onSuccess: () => {
      toast.success('Collectie verwijderd');
      qc.invalidateQueries({ queryKey: ['collections'] });
    },
  });

  const collections = data?.collections ?? [];

  return (
    <AppShell>
      <PageHeader
        title="Collecties"
        description="Smart (regel-gebaseerd) of manual (handmatig)."
        actions={
          <Button size="sm" onClick={() => setNewOpen(true)}>
            <Plus className="h-4 w-4" />
            Nieuwe collectie
          </Button>
        }
      />
      <PageBody>
        <Card>
          <Table>
            <THead>
              <TR className="hover:bg-transparent">
                <TH>Naam</TH>
                <TH>Slug</TH>
                <TH>Type</TH>
                <TH className="text-right">Producten</TH>
                <TH>Status</TH>
                <TH></TH>
              </TR>
            </THead>
            <TBody>
              {collections.map((c) => (
                <TR key={c.id}>
                  <TD>
                    <Link to={`/cms/collections/${c.id}`} className="font-medium text-[#F5F5F5] hover:text-[#00FF6A]">
                      {c.name}
                    </Link>
                  </TD>
                  <TD className="text-xs text-[#999]">{c.slug}</TD>
                  <TD>
                    <Badge variant={c.type === 'smart' ? 'info' : 'default'}>{c.type}</Badge>
                  </TD>
                  <TD className="text-right tabular-nums">{c.product_count}</TD>
                  <TD>
                    {c.enabled ? <Badge variant="success">actief</Badge> : <Badge variant="muted">uit</Badge>}
                  </TD>
                  <TD className="text-right">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => {
                        if (confirm(`"${c.name}" verwijderen?`)) deleteMut.mutate(c.id);
                      }}
                    >
                      <Trash2 className="h-4 w-4 text-[#FF3B3B]" />
                    </Button>
                  </TD>
                </TR>
              ))}
            </TBody>
          </Table>
        </Card>
      </PageBody>

      <Dialog open={newOpen} onOpenChange={setNewOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Nieuwe collectie</DialogTitle>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label>Naam</Label>
              <Input
                className="mt-1"
                value={form.name}
                onChange={(e) => {
                  const name = e.target.value;
                  setForm({
                    ...form,
                    name,
                    slug: form.slug || name.toLowerCase().replace(/[^a-z0-9]+/g, '-'),
                  });
                }}
              />
            </div>
            <div>
              <Label>Slug</Label>
              <Input className="mt-1" value={form.slug} onChange={(e) => setForm({ ...form, slug: e.target.value })} />
            </div>
            <div>
              <Label>Type</Label>
              <Select className="mt-1" value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value as 'smart' | 'manual' })}>
                <option value="smart">Smart (regel-gebaseerd)</option>
                <option value="manual">Manual (handmatig)</option>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setNewOpen(false)}>Annuleer</Button>
            <Button onClick={() => createMut.mutate()} disabled={createMut.isPending || !form.name || !form.slug}>
              Aanmaken
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </AppShell>
  );
}
