import { useCallback, useEffect, useRef, useState } from 'react';
import { ChevronRight, LoaderCircleIcon, Upload } from 'lucide-react';
import { Button } from '@rutatiina/ui/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@rutatiina/ui/components/ui/dialog';
import { notify } from '@rutatiina/ui/lib/notify';
import { FileTile } from '@rutatiina/media/components/file-tile';
import {
  acceptAttribute,
  formatBytes,
  rejectedFiles,
} from '@rutatiina/media/lib/format';
import { mediaRequest } from '@rutatiina/media/lib/request';
import type {
  FolderContents,
  MediaFile,
  MediaPickerProps,
} from '@rutatiina/media/types';

/**
 * Chooses a file from the file manager, or uploads one. Other modules render it by
 * name so they do not depend on this module:
 *
 *     const MediaPicker = getComponent<MediaPickerProps>('media-picker');
 *     {MediaPicker && <MediaPicker open={open} onOpenChange={setOpen} onSelect={…} images />}
 */
export function MediaPicker({
  open,
  onOpenChange,
  onSelect,
  images = false,
  title = 'Choose a file',
}: MediaPickerProps) {
  const input = useRef<HTMLInputElement>(null);
  const [contents, setContents] = useState<FolderContents | null>(null);
  const [selected, setSelected] = useState<MediaFile | null>(null);
  const [loading, setLoading] = useState(false);

  const load = useCallback(
    (folder?: number) => {
      const query = new URLSearchParams();
      if (folder) query.set('folder', String(folder));
      if (images) query.set('images', '1');

      setLoading(true);
      mediaRequest<FolderContents>(`/files/browse?${query}`)
        .then((data) => {
          setContents(data);
          setSelected(null);
        })
        .catch((error: Error) => notify.error(error.message))
        .finally(() => setLoading(false));
    },
    [images],
  );

  useEffect(() => {
    if (open) load();
  }, [open, load]);

  const upload = (list: FileList) => {
    if (!contents) return;
    const files = Array.from(list);
    const rejected = rejectedFiles(
      files,
      images
        ? {
            ...contents.limits,
            extensions: ['jpg', 'jpeg', 'png', 'gif', 'webp'],
          }
        : contents.limits,
    );

    if (rejected.length) {
      notify.error(rejected.join(' '));

      return;
    }

    const body = new FormData();
    body.append('folder_id', String(contents.folder.id));
    files.forEach((file) => body.append('files[]', file));

    setLoading(true);
    mediaRequest<{ data: MediaFile[] }>('/files/upload', {
      method: 'POST',
      body,
    })
      .then(({ data }) => {
        load(contents.folder.id);
        if (data[0]) setSelected(data[0]);
      })
      .catch((error: Error) => {
        notify.error(error.message);
        setLoading(false);
      });
  };

  const choose = () => {
    if (!selected) return;
    onSelect(selected);
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-4xl">
        <DialogHeader>
          <DialogTitle>{title}</DialogTitle>
          <DialogDescription className="flex flex-wrap items-center gap-1">
            {contents?.trail.map((step, index) => (
              <span key={step.id} className="flex items-center gap-1">
                {index > 0 && <ChevronRight className="size-3.5" />}
                <button
                  type="button"
                  className="hover:text-foreground"
                  onClick={() => load(index === 0 ? undefined : step.id)}
                >
                  {step.name}
                </button>
              </span>
            ))}
          </DialogDescription>
        </DialogHeader>

        <div className="max-h-[55vh] min-h-48 overflow-y-auto">
          {!contents || (loading && !contents.files.length) ? (
            <div className="flex justify-center py-16">
              <LoaderCircleIcon className="text-muted-foreground animate-spin" />
            </div>
          ) : contents.folders.length === 0 && contents.files.length === 0 ? (
            <p className="text-muted-foreground py-16 text-center text-sm">
              {images ? 'No images here yet.' : 'No files here yet.'}
            </p>
          ) : (
            <div className="grid grid-cols-2 gap-3 sm:grid-cols-4 lg:grid-cols-5">
              {contents.folders.map((folder) => (
                <FileTile
                  key={`folder-${folder.id}`}
                  folder
                  title={folder.name}
                  onOpen={() => load(folder.id)}
                />
              ))}
              {contents.files.map((file) => (
                <FileTile
                  key={`file-${file.id}`}
                  file={file}
                  title={file.name}
                  subtitle={formatBytes(file.size)}
                  selected={selected?.id === file.id}
                  onOpen={() => setSelected(file)}
                />
              ))}
            </div>
          )}
        </div>

        <DialogFooter className="sm:justify-between">
          <div>
            {contents?.can.manage && (
              <>
                <Button
                  variant="outline"
                  disabled={loading}
                  onClick={() => input.current?.click()}
                >
                  <Upload />
                  Upload
                </Button>
                <input
                  ref={input}
                  type="file"
                  multiple
                  hidden
                  accept={acceptAttribute(contents.limits.extensions, images)}
                  onChange={(event) => {
                    if (event.target.files) upload(event.target.files);
                    event.target.value = '';
                  }}
                />
              </>
            )}
          </div>
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancel
            </Button>
            <Button disabled={!selected} onClick={choose}>
              Choose
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
