import type { Torrent } from '../shared';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useTorrentMutations } from '../useTransmissionData';

// torrent-set-location does two unrelated things depending on one boolean, so the dialog asks in words
// rather than showing a checkbox called "move".
//
//   move: true  — physically relocate the data, then point the torrent at the new place
//   move: false — the data is ALREADY there; just re-point the torrent (this is how you recover after
//                 moving files by hand, and it is also how you lose a torrent if you pick it by mistake)

type MoveTorrentDialogProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  targets: Torrent[];
  /** Every distinct download dir currently in use, offered as one-click destinations. */
  knownDirs: string[];
};

export const MoveTorrentDialog = ({ open, onOpenChange, targets, knownDirs }: MoveTorrentDialogProps) => {
  const { setLocation } = useTorrentMutations();
  const [location, setLocationValue] = useState('');
  const [move, setMove] = useState(true);

  useEffect(() => {
    if (!open) return;
    // Seed with the current location when they all share one — the common case is a small edit to it.
    const dirs = new Set(targets.map((t) => t.downloadDir));
    setLocationValue(dirs.size === 1 ? [...dirs][0]! : '');
    setMove(true);
  }, [open, targets]);

  const submit = async () => {
    await setLocation.mutateAsync({ ids: targets.map((t) => t.id), location: location.trim(), move });
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>Set location</DialogTitle>
          <DialogDescription>
            {targets.length === 1 ? targets[0]!.name : `${targets.length} torrents`}
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-1.5">
            <Label htmlFor="tr-move-path">Destination</Label>
            <Input
              id="tr-move-path"
              value={location}
              onChange={(ev) => setLocationValue(ev.target.value)}
              placeholder="/downloads/complete"
              className="font-mono text-xs"
            />
          </div>

          {knownDirs.length > 0 && (
            <div className="flex flex-wrap gap-1.5">
              {knownDirs.map((dir) => (
                <button
                  key={dir}
                  type="button"
                  onClick={() => setLocationValue(dir)}
                  title={dir}
                  className="max-w-full truncate rounded bg-muted px-2 py-1 text-xs hover:bg-muted/70"
                >
                  {dir}
                </button>
              ))}
            </div>
          )}

          <div className="space-y-2">
            <label className="flex items-start gap-2.5 rounded-lg border border-border p-3 text-sm">
              <input type="radio" name="tr-move-mode" className="mt-1" checked={move} onChange={() => setMove(true)} />
              <span>
                <span className="font-medium">Move the data there</span>
                <span className="mt-0.5 block text-xs text-muted-foreground">
                  Transmission copies the files to the new location and removes the originals.
                </span>
              </span>
            </label>
            <label className="flex items-start gap-2.5 rounded-lg border border-border p-3 text-sm">
              <input
                type="radio"
                name="tr-move-mode"
                className="mt-1"
                checked={!move}
                onChange={() => setMove(false)}
              />
              <span>
                <span className="font-medium">The data is already there</span>
                <span className="mt-0.5 block text-xs text-muted-foreground">
                  Nothing is copied. Use this after moving files yourself — if the files are not there, the torrent will
                  re-download.
                </span>
              </span>
            </label>
          </div>
        </div>

        <DialogFooter>
          <Button variant="ghost" onClick={() => onOpenChange(false)}>
            Cancel
          </Button>
          <Button onClick={submit} disabled={!location.trim() || setLocation.isPending}>
            Apply
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};
