import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import {
  DndContext, closestCenter, KeyboardSensor, PointerSensor, useSensor, useSensors,
  type DragEndEvent,
} from '@dnd-kit/core';
import {
  arrayMove, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Plus, Trash2, Eye, EyeOff, GripVertical, 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';

interface Section {
  id: string;
  type: string;
  title: string | null;
  config: Record<string, unknown>;
  sort_order: number;
  enabled: boolean;
}

const SECTION_TYPES = [
  { value: 'hero', label: 'Hero banner' },
  { value: 'featured-brands', label: 'Uitgelichte merken' },
  { value: 'trending', label: 'Trending sneakers' },
  { value: 'new-arrivals', label: 'Nieuwe binnen' },
  { value: 'deals', label: 'Aanbiedingen' },
  { value: 'collection', label: 'Collectie' },
  { value: 'releases', label: 'Release kalender' },
  { value: 'newsletter', label: 'Nieuwsbrief CTA' },
];

export function HomepageEditor() {
  const qc = useQueryClient();
  const [sections, setSections] = useState<Section[]>([]);
  const [dirty, setDirty] = useState(false);

  const { data, isLoading } = useQuery({
    queryKey: ['homepage-sections'],
    queryFn: () => api.get<{ sections: Section[] }>('/homepage'),
  });

  useEffect(() => {
    if (data?.sections) {
      setSections(data.sections);
      setDirty(false);
    }
  }, [data?.sections]);

  const reorderMut = useMutation({
    mutationFn: (ids: string[]) => api.post('/homepage/reorder', { ids }),
    onSuccess: () => {
      toast.success('Volgorde opgeslagen');
      qc.invalidateQueries({ queryKey: ['homepage-sections'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const createMut = useMutation({
    mutationFn: (body: Partial<Section>) => api.post<{ section: Section }>('/homepage', body),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['homepage-sections'] }),
  });

  const updateMut = useMutation({
    mutationFn: ({ id, body }: { id: string; body: Partial<Section> }) =>
      api.put<{ section: Section }>(`/homepage/${id}`, body),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['homepage-sections'] }),
  });

  const deleteMut = useMutation({
    mutationFn: (id: string) => api.delete(`/homepage/${id}`),
    onSuccess: () => {
      toast.success('Sectie verwijderd');
      qc.invalidateQueries({ queryKey: ['homepage-sections'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
  );

  function onDragEnd(ev: DragEndEvent) {
    const { active, over } = ev;
    if (!over || active.id === over.id) return;
    const oldIndex = sections.findIndex((s) => s.id === active.id);
    const newIndex = sections.findIndex((s) => s.id === over.id);
    setSections(arrayMove(sections, oldIndex, newIndex));
    setDirty(true);
  }

  function addSection() {
    createMut.mutate({
      type: 'hero',
      title: 'Nieuwe sectie',
      config: {},
      sort_order: sections.length,
      enabled: true,
    });
  }

  return (
    <AppShell>
      <PageHeader
        title="Homepage editor"
        description="Drag-drop secties om de volgorde aan te passen."
        actions={
          <>
            {dirty && (
              <Button
                size="sm"
                onClick={() => reorderMut.mutate(sections.map((s) => s.id))}
                disabled={reorderMut.isPending}
              >
                <Save className="h-4 w-4" />
                Volgorde opslaan
              </Button>
            )}
            <Button size="sm" onClick={addSection} variant="secondary">
              <Plus className="h-4 w-4" />
              Sectie toevoegen
            </Button>
          </>
        }
      />
      <PageBody>
        {isLoading ? (
          <Card>
            <CardContent>Laden...</CardContent>
          </Card>
        ) : sections.length === 0 ? (
          <Card>
            <CardContent className="text-center py-12">
              <p className="text-sm text-[#999] mb-4">Nog geen secties.</p>
              <Button onClick={addSection}>
                <Plus className="h-4 w-4" />
                Eerste sectie toevoegen
              </Button>
            </CardContent>
          </Card>
        ) : (
          <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
            <SortableContext items={sections.map((s) => s.id)} strategy={verticalListSortingStrategy}>
              <div className="space-y-3 max-w-4xl">
                {sections.map((s) => (
                  <SortableSection
                    key={s.id}
                    section={s}
                    onUpdate={(body) => updateMut.mutate({ id: s.id, body })}
                    onDelete={() => {
                      if (confirm(`Sectie "${s.title ?? s.type}" verwijderen?`)) deleteMut.mutate(s.id);
                    }}
                  />
                ))}
              </div>
            </SortableContext>
          </DndContext>
        )}
      </PageBody>
    </AppShell>
  );
}

function SortableSection({
  section,
  onUpdate,
  onDelete,
}: {
  section: Section;
  onUpdate: (body: Partial<Section>) => void;
  onDelete: () => void;
}) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: section.id });
  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };
  const [local, setLocal] = useState(section);

  useEffect(() => setLocal(section), [section]);

  const dirty = JSON.stringify(local) !== JSON.stringify(section);

  return (
    <div ref={setNodeRef} style={style} className="bg-[#141414] border border-[#333] rounded-xl">
      <div className="flex items-start gap-3 px-5 py-4">
        <button
          {...attributes}
          {...listeners}
          className="mt-2 text-[#666] hover:text-[#F5F5F5] cursor-grab active:cursor-grabbing"
        >
          <GripVertical className="h-5 w-5" />
        </button>
        <div className="flex-1 grid grid-cols-12 gap-3">
          <div className="col-span-4">
            <Label>Type</Label>
            <Select className="mt-1" value={local.type} onChange={(e) => setLocal({ ...local, type: e.target.value })}>
              {SECTION_TYPES.map((t) => (
                <option key={t.value} value={t.value}>{t.label}</option>
              ))}
            </Select>
          </div>
          <div className="col-span-8">
            <Label>Titel</Label>
            <Input
              className="mt-1"
              value={local.title ?? ''}
              onChange={(e) => setLocal({ ...local, title: e.target.value })}
            />
          </div>
        </div>
        <div className="flex items-center gap-1 pt-6">
          {dirty && (
            <Button size="sm" onClick={() => onUpdate({ type: local.type, title: local.title })}>
              <Save className="h-4 w-4" />
            </Button>
          )}
          <Button
            variant="ghost"
            size="icon"
            onClick={() => onUpdate({ enabled: !local.enabled })}
            title={local.enabled ? 'Verberg' : 'Toon'}
          >
            {local.enabled ? (
              <Eye className="h-4 w-4 text-[#00FF6A]" />
            ) : (
              <EyeOff className="h-4 w-4 text-[#666]" />
            )}
          </Button>
          <Button variant="ghost" size="icon" onClick={onDelete}>
            <Trash2 className="h-4 w-4 text-[#FF3B3B]" />
          </Button>
        </div>
      </div>
    </div>
  );
}
