'use client';

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

interface AdminOverrideDialogProps {
  sessionId: string;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  projectIds: string[];
}

export function AdminOverrideDialog({
  sessionId,
  open,
  onOpenChange,
  projectIds
}: AdminOverrideDialogProps) {
  const utils = trpc.useUtils();
  const [rankings, setRankings] = useState<Record<string, number>>({});
  const [reason, setReason] = useState('');

  const { data: session } = trpc.deliberation.getSession.useQuery(
    { sessionId },
    { enabled: open, refetchInterval: 10_000 }
  );

  const adminDecideMutation = trpc.deliberation.adminDecide.useMutation({
    onSuccess: () => {
      utils.deliberation.getSession.invalidate();
      utils.deliberation.aggregate.invalidate();
      toast.success('Admin override applied successfully');
      onOpenChange(false);
      setRankings({});
      setReason('');
    },
    onError: (err) => {
      toast.error(err.message);
    }
  });

  const handleSubmit = () => {
    if (!reason.trim()) {
      toast.error('Reason is required for admin override');
      return;
    }

    const rankingsArray = Object.entries(rankings).map(([projectId, rank]) => ({
      projectId,
      rank
    }));

    if (rankingsArray.length === 0) {
      toast.error('Please assign at least one rank');
      return;
    }

    adminDecideMutation.mutate({
      sessionId,
      rankings: rankingsArray,
      reason: reason.trim()
    });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Admin Override</DialogTitle>
          <DialogDescription>
            Manually set the final rankings for this deliberation session. This action will be
            audited.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-3">
            <Label>Project Rankings</Label>
            <div className="space-y-2">
              {projectIds.map((projectId) => {
                const project = session?.results?.find((r) => r.project.id === projectId)?.project;
                return (
                  <div key={projectId} className="flex items-center gap-3">
                    <Input
                      type="number"
                      min="1"
                      placeholder="Rank"
                      value={rankings[projectId] || ''}
                      onChange={(e) =>
                        setRankings({
                          ...rankings,
                          [projectId]: parseInt(e.target.value) || 0
                        })
                      }
                      className="w-20"
                    />
                    <span className="flex-1 text-sm">{project?.title || projectId}</span>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="reason">Reason (Required) *</Label>
            <Textarea
              id="reason"
              value={reason}
              onChange={(e) => setReason(e.target.value)}
              placeholder="Explain why this admin override is necessary..."
              rows={3}
              required
            />
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button
            onClick={handleSubmit}
            disabled={adminDecideMutation.isPending || !reason.trim()}
          >
            {adminDecideMutation.isPending ? 'Applying...' : 'Apply Override'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
