'use client';

import { useState, useRef } from 'react';
import { Upload } from 'lucide-react';

interface FileUploadProps {
  onUploadSuccess: (chart: { id: number; name: string }) => void;
}

export default function FileUpload({ onUploadSuccess }: FileUploadProps) {
  const [isUploading, setIsUploading] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setIsUploading(true);
    setMessage(null);

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();

      if (response.ok) {
        setMessage({
          type: 'success',
          text: `Uploaded ${data.count} candles`,
        });
        onUploadSuccess(data.chart);
      } else {
        setMessage({
          type: 'error',
          text: data.error || 'Upload failed',
        });
      }
    } catch (error: any) {
      setMessage({
        type: 'error',
        text: error.message || 'Upload failed',
      });
    } finally {
      setIsUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  return (
    <div>
      <input
        ref={fileInputRef}
        type="file"
        accept=".csv"
        onChange={handleFileChange}
        disabled={isUploading}
        className="hidden"
      />
      <button
        onClick={() => fileInputRef.current?.click()}
        disabled={isUploading}
        className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded border border-border bg-secondary/30 hover:bg-secondary text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50"
      >
        <Upload className="w-3 h-3" />
        {isUploading ? 'Uploading...' : 'Upload CSV'}
      </button>

      {message && (
        <p className={`mt-1 text-[10px] ${message.type === 'success' ? 'text-green-600' : 'text-destructive'}`}>
          {message.text}
        </p>
      )}
    </div>
  );
}
