"use client";

import React, { useState, useEffect } from 'react';
import { Folder, FileText, ChevronRight, Loader2 } from 'lucide-react';

interface MissionFile {
  type: 'folder' | 'file';
  name: string;
  path: string;
  key: string;
  size?: number;
  lastModified?: string;
}

interface MissionFilesViewProps {
  missionId: string;
  onFileSelect: (file: MissionFile) => void;
  selectedFileKey?: string;
  initialPath?: string; // Optional initial path (e.g., "attachments")
}

export const MissionFilesView: React.FC<MissionFilesViewProps> = ({
  missionId,
  onFileSelect,
  selectedFileKey,
  initialPath = 'attachments' // Default to attachments folder
}) => {
  const [files, setFiles] = useState<MissionFile[]>([]);
  const [currentPath, setCurrentPath] = useState<string>(initialPath);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!missionId) return;
    
    const fetchFiles = async () => {
      try {
        setIsLoading(true);
        setError(null);
        const url = `/api/missions/${missionId}/files${currentPath ? `?path=${encodeURIComponent(currentPath)}` : ''}`;
        const response = await fetch(url);
        
        if (!response.ok) {
          throw new Error('Failed to fetch files');
        }
        
        const data = await response.json();
        setFiles(data.files || []);
      } catch (err) {
        console.error('Error fetching mission files:', err);
        setError(err instanceof Error ? err.message : 'Failed to load files');
      } finally {
        setIsLoading(false);
      }
    };

    fetchFiles();
  }, [missionId, currentPath]);

  const handleItemClick = (item: MissionFile) => {
    if (item.type === 'folder') {
      // Navigate into folder
      const newPath = item.path.replace(`missions/${missionId}/`, '').replace(/\/$/, '');
      setCurrentPath(newPath);
    } else {
      // Select file
      onFileSelect(item);
    }
  };

  const handleBack = () => {
    const pathParts = currentPath.split('/').filter(Boolean);
    pathParts.pop();
    setCurrentPath(pathParts.join('/'));
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-full">
        <Loader2 className="h-6 w-6 animate-spin text-carnet-text-muted" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="text-center">
          <p className="text-red-500 mb-2">Erreur</p>
          <p className="text-carnet-text-muted text-sm">{error}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full bg-carnet-bg">
      <div className="p-4 border-b border-carnet-border">
        <div className="flex items-center space-x-2">
          <Folder className="h-5 w-5 text-carnet-text-primary" />
          <h2 className="text-lg font-semibold text-carnet-text-primary">
            {currentPath ? currentPath.split('/').pop() : 'Fichiers'}
          </h2>
          {currentPath && (
            <button
              onClick={handleBack}
              className="ml-auto text-sm text-carnet-text-muted hover:text-carnet-text-primary"
            >
              Retour
            </button>
          )}
        </div>
      </div>
      
      <div className="flex-1 overflow-y-auto">
        {files.length === 0 ? (
          <div className="flex items-center justify-center h-full">
            <p className="text-carnet-text-muted">Aucun fichier</p>
          </div>
        ) : (
          <ul className="divide-y divide-carnet-border">
            {files.map((file) => {
              const Icon = file.type === 'folder' ? Folder : FileText;
              return (
                <li
                  key={file.key}
                  onClick={() => handleItemClick(file)}
                  className={`p-4 hover:bg-carnet-hover cursor-pointer flex items-center space-x-2 ${
                    selectedFileKey === file.key ? 'bg-carnet-hover' : ''
                  }`}
                >
                  <Icon className="h-4 w-4 text-carnet-text-muted" />
                  <span className="flex-1 text-sm text-carnet-text-primary">{file.name}</span>
                  {file.type === 'folder' && (
                    <ChevronRight className="h-4 w-4 text-carnet-text-muted" />
                  )}
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </div>
  );
};
