import type { Meta, StoryObj } from '@storybook/react';
import { FileUpload } from './file-upload';
import { useFileUpload } from './use-file-upload';
import React from 'react';
import { Upload, X, FileIcon, AlertCircle } from 'lucide-react';

const meta: Meta<typeof FileUpload> = {
  title: 'UI/FileUpload',
  component: FileUpload,
  render: args => <FileUpload {...args} />,
  argTypes: {
    multiple: { control: 'boolean' },
    disabled: { control: 'boolean' },
    size: { control: 'radio', options: ['default', 'compact'] },
  },
};

export default meta;
type Story = StoryObj<typeof FileUpload>;

export const Default: Story = {
  args: {
    accept: 'image/*,.pdf',
    multiple: false,
  },
  render: args => (
    <div className="w-[500px]">
      <FileUpload {...args} onFilesChange={files => console.log('Files:', files)} />
    </div>
  ),
};

export const Multiple: Story = {
  args: {
    accept: '*',
    multiple: true,
  },
  render: args => (
    <div className="w-[500px]">
      <FileUpload {...args} onFilesChange={files => console.log('Multiple Files:', files)} />
    </div>
  ),
};

export const ImageOnly: Story = {
  args: {
    accept: 'image/*',
    multiple: false,
    maxSize: 1024 * 1024, // 1MB
  },
  render: args => (
    <div className="w-[500px]">
      <FileUpload {...args} onFilesChange={files => console.log('Image:', files)} />
    </div>
  ),
};

export const Compact: Story = {
  args: {
    accept: '*',
    multiple: true,
    size: 'compact',
  },
  render: args => (
    <div className="w-[360px]">
      <FileUpload {...args} onFilesChange={files => console.log('Files:', files)} />
    </div>
  ),
};

export const CustomLabels: Story = {
  args: {
    accept: '*',
    multiple: true,
  },
  render: args => (
    <div className="w-[500px]">
      <FileUpload
        {...args}
        uploadLabel="Clique para enviar"
        dragAndDropLabel="ou arraste e solte"
        multipleFilesLabel="Até {count} arquivos"
        singleFileLabel="1 arquivo"
        maxSizeLabel="Máx {size}MB"
        sizeErrorLabel="{count} arquivo(s) excedem o limite de {size}MB e não foram adicionados."
        countErrorLabel="Apenas {max} arquivo(s) permitido(s). {count} arquivo(s) não foram adicionados."
        onFilesChange={files => console.log('Files:', files)}
      />
    </div>
  ),
};

/**
 * ## useFileUpload — Headless Hook
 *
 * Use `useFileUpload` when you need the full drag-and-drop logic but want to
 * render a completely custom drop-zone UI. The hook returns all state and
 * handlers; you wire them to whatever markup you like.
 *
 * ```tsx
 * import { useFileUpload } from '@xertica/ui/file-upload';
 *
 * const {
 *   files, dragActive, errorMessage, inputRef,
 *   handleDrag, handleDrop, handleChange, removeFile, openFileDialog,
 * } = useFileUpload({ maxFiles: 3, maxSize: 10 * 1024 * 1024 });
 * ```
 */
export const HeadlessHook: Story = {
  name: 'useFileUpload (headless)',
  render: () => {
    const {
      files,
      dragActive,
      errorMessage,
      inputRef,
      handleDrag,
      handleDrop,
      handleChange,
      removeFile,
      openFileDialog,
    } = useFileUpload({
      maxFiles: 3,
      maxSize: 2 * 1024 * 1024, // 2MB
      onFilesChange: f => console.log('files changed', f),
    });

    return (
      <div className="w-[500px] space-y-3">
        {/* Custom drop-zone — completely different from the default FileUpload UI */}
        <div
          onDragEnter={handleDrag}
          onDragLeave={handleDrag}
          onDragOver={handleDrag}
          onDrop={handleDrop}
          onClick={openFileDialog}
          className={[
            'flex cursor-pointer flex-col items-center gap-2 rounded-xl border-2 border-dashed p-10 text-center transition-all',
            dragActive
              ? 'border-blue-500 bg-blue-50 text-blue-700'
              : 'border-gray-300 bg-gray-50 text-gray-500 hover:border-gray-400',
          ].join(' ')}
        >
          <Upload className="h-8 w-8" />
          <p className="text-sm font-medium">
            {dragActive ? 'Drop files here…' : 'Drag files or click to browse'}
          </p>
          <p className="text-xs text-gray-400">Up to 3 files · Max 2 MB each</p>
          <input ref={inputRef} type="file" className="hidden" multiple onChange={handleChange} />
        </div>

        {errorMessage && (
          <div className="flex items-center gap-2 rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600">
            <AlertCircle className="h-4 w-4 shrink-0" />
            {errorMessage}
          </div>
        )}

        {files.length > 0 && (
          <ul className="space-y-1">
            {files.map((file, i) => (
              <li
                key={i}
                className="flex items-center justify-between rounded-lg border bg-white px-3 py-2 text-sm"
              >
                <span className="flex items-center gap-2">
                  <FileIcon className="h-4 w-4 text-gray-400" />
                  {file.name}
                </span>
                <button onClick={() => removeFile(i)} className="text-gray-400 hover:text-red-500">
                  <X className="h-4 w-4" />
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>
    );
  },
};
