'use client';

import { useState } from 'react';
import Link from 'next/link';
import type { Route } from 'next';
import { useParams } from 'next/navigation';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Plus, Users } from 'lucide-react';
import { toast } from 'sonner';

import { PageHeader } from '@/components/shared/page-header';
import { PermissionGate } from '@/components/shared/permission-gate';
import { EmptyState } from '@/components/shared/empty-state';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface ClientGroupRow {
  id: string;
  name: string;
  description: string | null;
  color: string;
  memberCount: number;
}

export function ClientGroupsList() {
  const params = useParams<{ portSlug: string }>();
  const portSlug = params?.portSlug ?? '';
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [color, setColor] = useState('#6B7280');

  const { data, isLoading } = useQuery<{ data: ClientGroupRow[] }>({
    queryKey: ['client-groups'],
    queryFn: () => apiFetch('/api/v1/client-groups'),
  });

  const create = useMutation({
    mutationFn: () =>
      apiFetch('/api/v1/client-groups', {
        method: 'POST',
        body: { name: name.trim(), description: description.trim() || null, color },
      }),
    onSuccess: () => {
      toast.success('Group created');
      qc.invalidateQueries({ queryKey: ['client-groups'] });
      setOpen(false);
      setName('');
      setDescription('');
      setColor('#6B7280');
    },
    onError: (err) => toastError(err),
  });

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

  return (
    <div className="space-y-6">
      <PageHeader
        title="Client Groups"
        eyebrow="Mailing"
        description="Group clients into mailing lists. View members, copy their emails, and (once wired) sync to Mailchimp."
        variant="gradient"
        actions={
          <PermissionGate resource="client_groups" action="manage">
            <Button onClick={() => setOpen(true)}>
              <Plus className="me-1.5 h-4 w-4" aria-hidden />
              New group
            </Button>
          </PermissionGate>
        }
      />

      {isLoading ? (
        <p className="text-sm text-muted-foreground">Loading…</p>
      ) : groups.length === 0 ? (
        <EmptyState
          icon={Users}
          title="No groups yet"
          description="Create a group to start organising clients into mailing lists."
        />
      ) : (
        <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {groups.map((g) => (
            <Link
              key={g.id}
              href={`/${portSlug}/client-groups/${g.id}` as Route}
              className="group rounded-xl border border-border bg-card p-4 transition-colors hover:border-brand/40 hover:bg-muted/40"
            >
              <div className="flex items-center gap-2">
                <span
                  className="h-3 w-3 shrink-0 rounded-full"
                  style={{ backgroundColor: g.color }}
                  aria-hidden
                />
                <h3 className="truncate font-medium text-foreground">{g.name}</h3>
              </div>
              {g.description ? (
                <p className="mt-1 line-clamp-2 text-sm text-muted-foreground">{g.description}</p>
              ) : null}
              <p className="mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground">
                <Users className="h-3.5 w-3.5" aria-hidden />
                {g.memberCount} {g.memberCount === 1 ? 'member' : 'members'}
              </p>
            </Link>
          ))}
        </div>
      )}

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>New client group</DialogTitle>
            <DialogDescription>A named mailing/segment group for this port.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-1.5">
              <Label htmlFor="cg-name">Name</Label>
              <Input
                id="cg-name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="e.g. Newsletter subscribers"
                autoFocus
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="cg-desc">Description (optional)</Label>
              <Input
                id="cg-desc"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="cg-color">Color</Label>
              <input
                id="cg-color"
                type="color"
                value={color}
                onChange={(e) => setColor(e.target.value)}
                className="h-9 w-16 cursor-pointer rounded-md border border-border bg-background"
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setOpen(false)}>
              Cancel
            </Button>
            <Button onClick={() => create.mutate()} disabled={!name.trim() || create.isPending}>
              Create group
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
