import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { ArrowLeft, Save, Plus, X } from 'lucide-react';
import { api } from '../../lib/api-client';
import { AppShell, PageHeader, PageBody } from '../../layout/AppShell';
import { Button, Badge, Card, CardContent, Input, Label, Select, Textarea } from '../../components/ui/primitives';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '../../components/ui/tabs';

interface Rule {
  field: 'brand' | 'price' | 'gender' | 'is_sneaker' | 'in_stock';
  op: 'eq' | 'neq' | 'lt' | 'gt' | 'lte' | 'gte' | 'contains';
  value: string;
}
interface RuleSet {
  match: 'all' | 'any';
  rules: Rule[];
}

interface Collection {
  id: string;
  name: string;
  slug: string;
  type: 'smart' | 'manual';
  rules: RuleSet | null;
  sort_field: string;
  sort_dir: 'asc' | 'desc';
  item_limit: number;
  description: string | null;
  seo_title: string | null;
  seo_desc: string | null;
  enabled: boolean;
}

export function CollectionEditor() {
  const { id } = useParams<{ id: string }>();
  const qc = useQueryClient();
  const navigate = useNavigate();
  const [form, setForm] = useState<Partial<Collection> | null>(null);

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

  useEffect(() => {
    if (data?.collection) setForm(data.collection);
  }, [data?.collection]);

  const saveMut = useMutation({
    mutationFn: (body: Partial<Collection>) => api.put(`/collections/${id}`, body),
    onSuccess: () => {
      toast.success('Collectie opgeslagen');
      qc.invalidateQueries({ queryKey: ['collection', id] });
      qc.invalidateQueries({ queryKey: ['collections'] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  if (!form) {
    return (
      <AppShell>
        <PageHeader title="Laden..." />
      </AppShell>
    );
  }

  const rules: RuleSet = form.rules ?? { match: 'all', rules: [] };

  function updateRules(next: RuleSet) {
    setForm((f) => ({ ...f!, rules: next }));
  }
  function addRule() {
    updateRules({ ...rules, rules: [...rules.rules, { field: 'brand', op: 'eq', value: '' }] });
  }
  function updateRule(i: number, patch: Partial<Rule>) {
    const next = [...rules.rules];
    next[i] = { ...next[i], ...patch };
    updateRules({ ...rules, rules: next });
  }
  function removeRule(i: number) {
    const next = [...rules.rules];
    next.splice(i, 1);
    updateRules({ ...rules, rules: next });
  }

  return (
    <AppShell>
      <PageHeader
        title={form.name ?? ''}
        description={`${form.type} · ${form.slug}`}
        actions={
          <>
            <Button variant="ghost" size="sm" onClick={() => navigate('/cms/collections')}>
              <ArrowLeft className="h-4 w-4" />
              Terug
            </Button>
            <Button size="sm" onClick={() => saveMut.mutate(form)} disabled={saveMut.isPending}>
              <Save className="h-4 w-4" />
              Opslaan
            </Button>
          </>
        }
      />
      <PageBody>
        <Tabs defaultValue="config">
          <TabsList>
            <TabsTrigger value="config">Configuratie</TabsTrigger>
            <TabsTrigger value="rules">Regels</TabsTrigger>
            <TabsTrigger value="seo">SEO</TabsTrigger>
          </TabsList>

          <TabsContent value="config">
            <Card>
              <CardContent>
                <div className="grid grid-cols-2 gap-4 max-w-2xl">
                  <div>
                    <Label>Naam</Label>
                    <Input className="mt-1" value={form.name ?? ''} onChange={(e) => setForm({ ...form, name: e.target.value })} />
                  </div>
                  <div>
                    <Label>Slug</Label>
                    <Input className="mt-1" value={form.slug ?? ''} onChange={(e) => setForm({ ...form, slug: e.target.value })} />
                  </div>
                  <div>
                    <Label>Sorteer op</Label>
                    <Select className="mt-1" value={form.sort_field ?? 'performance_score'} onChange={(e) => setForm({ ...form, sort_field: e.target.value })}>
                      <option value="performance_score">Performance</option>
                      <option value="clicks_7d">Clicks 7d</option>
                      <option value="price">Prijs</option>
                      <option value="created_at">Datum</option>
                    </Select>
                  </div>
                  <div>
                    <Label>Richting</Label>
                    <Select className="mt-1" value={form.sort_dir ?? 'desc'} onChange={(e) => setForm({ ...form, sort_dir: e.target.value as 'asc' | 'desc' })}>
                      <option value="desc">Hoog naar laag</option>
                      <option value="asc">Laag naar hoog</option>
                    </Select>
                  </div>
                  <div>
                    <Label>Max. items</Label>
                    <Input type="number" min={1} max={1000} className="mt-1" value={form.item_limit ?? 50} onChange={(e) => setForm({ ...form, item_limit: Number(e.target.value) })} />
                  </div>
                  <div className="col-span-2">
                    <Label>Beschrijving</Label>
                    <Textarea className="mt-1" rows={3} value={form.description ?? ''} onChange={(e) => setForm({ ...form, description: e.target.value })} />
                  </div>
                  <label className="flex items-center gap-2 cursor-pointer col-span-2">
                    <input type="checkbox" checked={form.enabled ?? true} onChange={(e) => setForm({ ...form, enabled: e.target.checked })} />
                    <span className="text-sm text-[#F5F5F5]">Zichtbaar op de site</span>
                  </label>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="rules">
            <Card>
              <CardContent>
                {form.type !== 'smart' ? (
                  <p className="text-sm text-[#999]">Regels zijn alleen van toepassing op smart collecties.</p>
                ) : (
                  <div className="space-y-3">
                    <div className="flex items-center gap-2">
                      <span className="text-sm text-[#F5F5F5]">Match</span>
                      <Select
                        className="w-32"
                        value={rules.match}
                        onChange={(e) => updateRules({ ...rules, match: e.target.value as 'all' | 'any' })}
                      >
                        <option value="all">alle (AND)</option>
                        <option value="any">één (OR)</option>
                      </Select>
                      <span className="text-sm text-[#F5F5F5]">van onderstaande regels</span>
                    </div>
                    {rules.rules.map((r, i) => (
                      <div key={i} className="flex items-center gap-2">
                        <Select className="w-40" value={r.field} onChange={(e) => updateRule(i, { field: e.target.value as Rule['field'] })}>
                          <option value="brand">merk</option>
                          <option value="price">prijs</option>
                          <option value="gender">gender</option>
                          <option value="is_sneaker">is sneaker</option>
                          <option value="in_stock">op voorraad</option>
                        </Select>
                        <Select className="w-32" value={r.op} onChange={(e) => updateRule(i, { op: e.target.value as Rule['op'] })}>
                          <option value="eq">=</option>
                          <option value="neq">≠</option>
                          <option value="lt">&lt;</option>
                          <option value="lte">≤</option>
                          <option value="gt">&gt;</option>
                          <option value="gte">≥</option>
                          <option value="contains">bevat</option>
                        </Select>
                        <Input className="flex-1" value={r.value} onChange={(e) => updateRule(i, { value: e.target.value })} placeholder="waarde" />
                        <Button variant="ghost" size="icon" onClick={() => removeRule(i)}>
                          <X className="h-4 w-4 text-[#FF3B3B]" />
                        </Button>
                      </div>
                    ))}
                    <Button variant="secondary" size="sm" onClick={addRule}>
                      <Plus className="h-4 w-4" />
                      Regel toevoegen
                    </Button>
                    {rules.rules.length > 0 && (
                      <div className="mt-4 pt-4 border-t border-[#333]">
                        <p className="text-xs text-[#999] mb-2">Preview: matcht producten waar</p>
                        <div className="flex items-center flex-wrap gap-1">
                          {rules.rules.map((r, i) => (
                            <Badge key={i} variant="info">
                              {r.field} {r.op} "{r.value}"
                              {i < rules.rules.length - 1 && (
                                <span className="ml-1 text-[#999]">{rules.match === 'all' ? 'EN' : 'OF'}</span>
                              )}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="seo">
            <Card>
              <CardContent>
                <div className="space-y-4 max-w-2xl">
                  <div>
                    <Label>SEO titel</Label>
                    <Input className="mt-1" value={form.seo_title ?? ''} onChange={(e) => setForm({ ...form, seo_title: e.target.value })} />
                  </div>
                  <div>
                    <Label>SEO beschrijving</Label>
                    <Textarea className="mt-1" rows={3} value={form.seo_desc ?? ''} onChange={(e) => setForm({ ...form, seo_desc: e.target.value })} />
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </PageBody>
    </AppShell>
  );
}
