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 Template {
  id: number;
  name: string;
  type: string;
  created_at: string;
  updated_at: string;
}

export function EmailsList() {
  const qc = useQueryClient();
  const navigate = useNavigate();
  const [newOpen, setNewOpen] = useState(false);
  const [form, setForm] = useState({ name: '', type: 'newsletter' });

  const { data } = useQuery({
    queryKey: ['email-templates'],
    queryFn: () => api.get<{ templates: Template[] }>('/emails'),
  });

  const createMut = useMutation({
    mutationFn: () => api.post<{ template: Template }>('/emails', { ...form, blocks_json: [] }),
    onSuccess: (res) => {
      setNewOpen(false);
      navigate(`/cms/emails/${res.template.id}`);
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const deleteMut = useMutation({
    mutationFn: (id: number) => api.delete(`/emails/${id}`),
    onSuccess: () => {
      toast.success('Template verwijderd');
      qc.invalidateQueries({ queryKey: ['email-templates'] });
    },
  });

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

  return (
    <AppShell>
      <PageHeader
        title="Email templates"
        description="Block-based editor met Klaviyo-integratie."
        actions={
          <Button size="sm" onClick={() => setNewOpen(true)}>
            <Plus className="h-4 w-4" />
            Nieuwe template
          </Button>
        }
      />
      <PageBody>
        <Card>
          <Table>
            <THead>
              <TR className="hover:bg-transparent">
                <TH>Naam</TH>
                <TH>Type</TH>
                <TH>Bijgewerkt</TH>
                <TH></TH>
              </TR>
            </THead>
            <TBody>
              {templates.map((t) => (
                <TR key={t.id}>
                  <TD>
                    <Link to={`/cms/emails/${t.id}`} className="font-medium text-[#F5F5F5] hover:text-[#00FF6A]">
                      {t.name}
                    </Link>
                  </TD>
                  <TD>
                    <Badge variant="info">{t.type}</Badge>
                  </TD>
                  <TD className="text-xs text-[#999]">
                    {new Date(t.updated_at).toLocaleDateString('nl-NL')}
                  </TD>
                  <TD className="text-right">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => {
                        if (confirm(`Template "${t.name}" verwijderen?`)) deleteMut.mutate(t.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 email template</DialogTitle>
          </DialogHeader>
          <div className="space-y-3">
            <div>
              <Label>Naam</Label>
              <Input className="mt-1" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
            </div>
            <div>
              <Label>Type</Label>
              <Select className="mt-1" value={form.type} onChange={(e) => setForm({ ...form, type: e.target.value })}>
                <option value="newsletter">Newsletter</option>
                <option value="campaign">Campaign</option>
                <option value="transactional">Transactional</option>
                <option value="price-drop">Price drop alert</option>
                <option value="custom">Custom</option>
              </Select>
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setNewOpen(false)}>Annuleer</Button>
            <Button onClick={() => createMut.mutate()} disabled={!form.name || createMut.isPending}>Aanmaken</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </AppShell>
  );
}
