import type { Torrent } from '../shared';
import { useEffect, useState } from 'react';
import { TriangleAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { formatSize } from '../format';
import { useTorrentMutations } from '../useTransmissionData';

// Removing a torrent and deleting its data are one RPC apart and a very long way apart in consequence, so
// they are one dialog with an explicit opt-in rather than two menu items you can mis-click between.

type RemoveTorrentDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  targets: Torrent[];
  onRemoved?: () => void;
};

export const RemoveTorrentDialog = ({ open, onOpenChange, targets, onRemoved }: RemoveTorrentDialogProps) => {
  const { remove } = useTorrentMutations();
  const [deleteData, setDeleteData] = useState(false);

  // Re-arm on every open: "also delete the files" must never be inherited from the last time.
  useEffect(() => {
    if (open) setDeleteData(false);
  }, [open]);

  const bytes = targets.reduce((sum, t) => sum + (t.totalSize ?? 0), 0);
  const one = targets.length === 1 ? targets[0] : null;

  const confirm = async () => {
    await remove.mutateAsync({ ids: targets.map((t) => t.id), deleteLocalData: deleteData });
    onOpenChange(false);
    onRemoved?.();
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Remove {one ? 'torrent' : `${targets.length} torrents`}?</DialogTitle>
          <DialogDescription className="break-words">
            {one ? one.name : `${targets.length} torrents totalling ${formatSize(bytes)}.`}
          </DialogDescription>
        </DialogHeader>

        <label className="flex items-start gap-2.5 rounded-lg border border-border p-3 text-sm">
          <Checkbox className="mt-0.5" checked={deleteData} onCheckedChange={(v) => setDeleteData(v === true)} />
          <span>
            <span className="font-medium">Also delete the downloaded files</span>
            <span className="mt-0.5 block text-xs text-muted-foreground">
              {deleteData
                ? `${formatSize(bytes)} will be deleted from disk. This cannot be undone.`
                : 'The files stay on disk; only the torrent is removed.'}
            </span>
          </span>
        </label>

        {deleteData && (
          <div className="flex items-center gap-2 rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive">
            <TriangleAlert className="h-4 w-4 shrink-0" />
            Transmission deletes the data immediately — there is no trash.
          </div>
        )}

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button variant="destructive" onClick={confirm} disabled={remove.isPending}>
            {deleteData ? 'Remove and delete' : 'Remove'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
