import { useEffect, useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { trpc } from '@/lib/trpc';

interface CreateErrandDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function CreateErrandDialog({ open, onOpenChange }: CreateErrandDialogProps) {
  const [description, setDescription] = useState('');
  const [projectId, setProjectId] = useState('');
  const [baseBranch, setBaseBranch] = useState('');
  const [error, setError] = useState<string | null>(null);

  const navigate = useNavigate();
  const utils = trpc.useUtils();

  const projectsQuery = trpc.listProjects.useQuery();

  const createMutation = trpc.errand.create.useMutation({
    onSuccess: (data) => {
      toast.success('Errand started');
      onOpenChange(false);
      utils.errand.list.invalidate();
      navigate({ to: '/errands', search: { selected: data.id } });
    },
    onError: (err) => {
      setError(err.message);
    },
  });

  useEffect(() => {
    if (open) {
      setDescription('');
      setProjectId('');
      setBaseBranch('');
      setError(null);
    }
  }, [open]);

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    createMutation.mutate({
      description: description.trim(),
      projectId,
      baseBranch: baseBranch.trim() || undefined,
    });
  }

  const canSubmit =
    description.trim().length > 0 &&
    description.length <= 200 &&
    projectId !== '' &&
    !createMutation.isPending;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>New Errand</DialogTitle>
          <DialogDescription>
            Start a small isolated change with a dedicated agent.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="errand-description">Description</Label>
            <Textarea
              id="errand-description"
              placeholder="Describe the small change to make…"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              rows={3}
              autoFocus
            />
            <p
              className={cn(
                'text-xs text-right',
                description.length >= 190 ? 'text-destructive' : 'text-muted-foreground',
              )}
            >
              {description.length} / 200
            </p>
          </div>
          <div className="space-y-2">
            <Label htmlFor="errand-project">Project</Label>
            <select
              id="errand-project"
              value={projectId}
              onChange={(e) => setProjectId(e.target.value)}
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
            >
              <option value="">Select a project…</option>
              {(projectsQuery.data ?? []).map((p) => (
                <option key={p.id} value={p.id}>
                  {p.name}
                </option>
              ))}
            </select>
          </div>
          <div className="space-y-2">
            <Label htmlFor="errand-base">
              Base Branch{' '}
              <span className="text-muted-foreground font-normal">(optional — defaults to main)</span>
            </Label>
            <Input
              id="errand-base"
              placeholder="main"
              value={baseBranch}
              onChange={(e) => setBaseBranch(e.target.value)}
            />
          </div>
          {error && <p className="text-sm text-destructive">{error}</p>}
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button type="submit" disabled={!canSubmit}>
              {createMutation.isPending ? 'Starting…' : 'New Errand'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
