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

interface Brand {
  slug: string;
  name: string;
  tagline: string | null;
  description: string | null;
  long_description: string | null;
  founded: string | null;
  headquarters: string | null;
  founders: string | null;
  logo_url: string | null;
  hero_image_url: string | null;
  popular_models: Array<{ name: string; slug?: string }>;
  seo_title: string | null;
  seo_description: string | null;
  enabled: boolean;
  sort_order: number;
}

export function BrandEditor() {
  const { slug } = useParams<{ slug: string }>();
  const navigate = useNavigate();
  const [form, setForm] = useState<Partial<Brand> | null>(null);

  const { data } = useQuery({
    queryKey: ['brand-content', slug],
    queryFn: () => api.get<{ brand: Brand }>(`/brands/${slug}`),
    enabled: !!slug,
  });

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

  const saveMut = useMutation({
    mutationFn: (body: Partial<Brand>) => api.put(`/brands/${slug}`, body),
    onSuccess: () => toast.success('Merk opgeslagen'),
    onError: (e: Error) => toast.error(e.message),
  });

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

  return (
    <AppShell>
      <PageHeader
        title={form.name ?? ''}
        description={slug}
        actions={
          <>
            <Button variant="ghost" size="sm" onClick={() => navigate('/cms/brands')}>
              <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="info">
          <TabsList>
            <TabsTrigger value="info">Info</TabsTrigger>
            <TabsTrigger value="content">Content</TabsTrigger>
            <TabsTrigger value="seo">SEO</TabsTrigger>
          </TabsList>

          <TabsContent value="info">
            <Card>
              <CardContent>
                <div className="grid grid-cols-2 gap-4 max-w-3xl">
                  <div>
                    <Label>Naam</Label>
                    <Input className="mt-1" value={form.name ?? ''} onChange={(e) => setForm({ ...form, name: e.target.value })} />
                  </div>
                  <div>
                    <Label>Tagline</Label>
                    <Input className="mt-1" value={form.tagline ?? ''} onChange={(e) => setForm({ ...form, tagline: e.target.value })} />
                  </div>
                  <div>
                    <Label>Opgericht</Label>
                    <Input className="mt-1" value={form.founded ?? ''} onChange={(e) => setForm({ ...form, founded: e.target.value })} placeholder="1964" />
                  </div>
                  <div>
                    <Label>Hoofdkwartier</Label>
                    <Input className="mt-1" value={form.headquarters ?? ''} onChange={(e) => setForm({ ...form, headquarters: e.target.value })} placeholder="Beaverton, Oregon" />
                  </div>
                  <div className="col-span-2">
                    <Label>Oprichters</Label>
                    <Input className="mt-1" value={form.founders ?? ''} onChange={(e) => setForm({ ...form, founders: e.target.value })} />
                  </div>
                  <div>
                    <Label>Logo URL</Label>
                    <Input className="mt-1" value={form.logo_url ?? ''} onChange={(e) => setForm({ ...form, logo_url: e.target.value })} />
                  </div>
                  <div>
                    <Label>Hero afbeelding URL</Label>
                    <Input className="mt-1" value={form.hero_image_url ?? ''} onChange={(e) => setForm({ ...form, hero_image_url: 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</span>
                  </label>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="content">
            <Card>
              <CardContent>
                <div className="space-y-4 max-w-3xl">
                  <div>
                    <Label>Korte beschrijving</Label>
                    <Textarea className="mt-1" rows={3} value={form.description ?? ''} onChange={(e) => setForm({ ...form, description: e.target.value })} />
                  </div>
                  <div>
                    <Label>Lange beschrijving (markdown)</Label>
                    <Textarea className="mt-1 font-mono text-xs" rows={12} value={form.long_description ?? ''} onChange={(e) => setForm({ ...form, long_description: e.target.value })} />
                  </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_description ?? ''} onChange={(e) => setForm({ ...form, seo_description: e.target.value })} />
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </PageBody>
    </AppShell>
  );
}
