import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { Plus, Trash2, Save } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Button, Badge, Card, CardContent, 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 Release {
  id: string;
  slug: string;
  title: string;
  brand: string;
  model: string | null;
  colorway: string | null;
  release_date: string;
  release_time: string | null;
  price_eur: number | null;
  style_code: string | null;
  image_url: string | null;
  hype_score: number;
  status: 'upcoming' | 'released' | 'cancelled';
}

export function ReleaseCalendar() {
  const qc = useQueryClient();
  const [statusFilter, setStatusFilter] = useState<string>('upcoming');
  const [editing, setEditing] = useState<Partial<Release> | null>(null);

  const { data } = useQuery({
    queryKey: ['releases', statusFilter],
    queryFn: () =>
      api.get<{ releases: Release[] }>('/releases', statusFilter ? { status: statusFilter } : undefined),
  });

  const saveMut = useMutation({
    mutationFn: (body: Partial<Release>) => {
      if (body.id) return api.put(`/releases/${body.id}`, body);
      return api.post('/releases', body);
    },
    onSuccess: () => {
      toast.success('Release opgeslagen');
      setEditing(null);
      qc.invalidateQueries({ queryKey: ['releases'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

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

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

  return (
    <AppShell>
      <PageHeader
        title="Release kalender"
        description="Aankomende en uitgekomen sneaker-launches."
        actions={
          <Button
            size="sm"
            onClick={() =>
              setEditing({
                slug: '',
                title: '',
                brand: '',
                release_date: new Date().toISOString().slice(0, 10),
                hype_score: 50,
                status: 'upcoming',
              })
            }
          >
            <Plus className="h-4 w-4" />
            Nieuwe release
          </Button>
        }
      />
      <PageBody>
        <Card>
          <div className="px-5 py-3 border-b border-[#333] flex items-center gap-2">
            <Label>Status</Label>
            <Select className="w-40" value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
              <option value="">Alle</option>
              <option value="upcoming">Aankomend</option>
              <option value="released">Uitgebracht</option>
              <option value="cancelled">Geannuleerd</option>
            </Select>
          </div>
          <Table>
            <THead>
              <TR className="hover:bg-transparent">
                <TH>Datum</TH>
                <TH>Titel</TH>
                <TH>Merk</TH>
                <TH>Colorway</TH>
                <TH className="text-right">Prijs</TH>
                <TH className="text-right">Hype</TH>
                <TH>Status</TH>
                <TH></TH>
              </TR>
            </THead>
            <TBody>
              {releases.map((r) => (
                <TR key={r.id} className="cursor-pointer" onClick={() => setEditing(r)}>
                  <TD className="text-xs tabular-nums">
                    {new Date(r.release_date).toLocaleDateString('nl-NL', { day: '2-digit', month: 'short', year: 'numeric' })}
                    {r.release_time && <span className="text-[#666] ml-1">{r.release_time.slice(0, 5)}</span>}
                  </TD>
                  <TD className="font-medium">{r.title}</TD>
                  <TD className="text-xs text-[#999]">{r.brand}</TD>
                  <TD className="text-xs text-[#999]">{r.colorway ?? '—'}</TD>
                  <TD className="text-right tabular-nums">{r.price_eur ? `€${Number(r.price_eur).toFixed(0)}` : '—'}</TD>
                  <TD className="text-right tabular-nums">
                    <span className={r.hype_score > 70 ? 'text-[#00FF6A]' : r.hype_score > 40 ? 'text-[#FFA500]' : 'text-[#999]'}>
                      {r.hype_score}
                    </span>
                  </TD>
                  <TD>
                    <Badge variant={r.status === 'upcoming' ? 'info' : r.status === 'released' ? 'success' : 'muted'}>
                      {r.status}
                    </Badge>
                  </TD>
                  <TD className="text-right" onClick={(e) => e.stopPropagation()}>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => {
                        if (confirm(`"${r.title}" verwijderen?`)) deleteMut.mutate(r.id);
                      }}
                    >
                      <Trash2 className="h-4 w-4 text-[#FF3B3B]" />
                    </Button>
                  </TD>
                </TR>
              ))}
            </TBody>
          </Table>
        </Card>
      </PageBody>

      <Dialog open={!!editing} onOpenChange={(o) => !o && setEditing(null)}>
        <DialogContent size="lg">
          <DialogHeader>
            <DialogTitle>{editing?.id ? 'Release bewerken' : 'Nieuwe release'}</DialogTitle>
          </DialogHeader>
          {editing && (
            <div className="grid grid-cols-2 gap-3">
              <div className="col-span-2">
                <Label>Titel</Label>
                <Input className="mt-1" value={editing.title ?? ''} onChange={(e) => setEditing({ ...editing, title: e.target.value })} />
              </div>
              <div>
                <Label>Slug</Label>
                <Input className="mt-1" value={editing.slug ?? ''} onChange={(e) => setEditing({ ...editing, slug: e.target.value })} />
              </div>
              <div>
                <Label>Merk</Label>
                <Input className="mt-1" value={editing.brand ?? ''} onChange={(e) => setEditing({ ...editing, brand: e.target.value })} />
              </div>
              <div>
                <Label>Model</Label>
                <Input className="mt-1" value={editing.model ?? ''} onChange={(e) => setEditing({ ...editing, model: e.target.value })} />
              </div>
              <div>
                <Label>Colorway</Label>
                <Input className="mt-1" value={editing.colorway ?? ''} onChange={(e) => setEditing({ ...editing, colorway: e.target.value })} />
              </div>
              <div>
                <Label>Release datum</Label>
                <Input type="date" className="mt-1" value={editing.release_date ?? ''} onChange={(e) => setEditing({ ...editing, release_date: e.target.value })} />
              </div>
              <div>
                <Label>Tijd (optioneel)</Label>
                <Input type="time" className="mt-1" value={editing.release_time ?? ''} onChange={(e) => setEditing({ ...editing, release_time: e.target.value })} />
              </div>
              <div>
                <Label>Prijs (€)</Label>
                <Input
                  type="number"
                  step="0.01"
                  className="mt-1"
                  value={editing.price_eur ?? ''}
                  onChange={(e) => setEditing({ ...editing, price_eur: e.target.value ? Number(e.target.value) : null })}
                />
              </div>
              <div>
                <Label>Style code</Label>
                <Input className="mt-1" value={editing.style_code ?? ''} onChange={(e) => setEditing({ ...editing, style_code: e.target.value })} />
              </div>
              <div>
                <Label>Hype score (0-100)</Label>
                <Input
                  type="number"
                  min={0}
                  max={100}
                  className="mt-1"
                  value={editing.hype_score ?? 0}
                  onChange={(e) => setEditing({ ...editing, hype_score: Number(e.target.value) })}
                />
              </div>
              <div>
                <Label>Status</Label>
                <Select
                  className="mt-1"
                  value={editing.status ?? 'upcoming'}
                  onChange={(e) => setEditing({ ...editing, status: e.target.value as Release['status'] })}
                >
                  <option value="upcoming">Aankomend</option>
                  <option value="released">Uitgebracht</option>
                  <option value="cancelled">Geannuleerd</option>
                </Select>
              </div>
              <div className="col-span-2">
                <Label>Afbeelding URL</Label>
                <Input className="mt-1" value={editing.image_url ?? ''} onChange={(e) => setEditing({ ...editing, image_url: e.target.value })} />
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="ghost" onClick={() => setEditing(null)}>Annuleer</Button>
            <Button onClick={() => editing && saveMut.mutate(editing)} disabled={saveMut.isPending}>
              <Save className="h-4 w-4" />
              Opslaan
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </AppShell>
  );
}
