"use client";

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

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

interface MissionUser {
  role: string;
  userId: string;
}

interface Mission {
  id: string;
  name: string;
  creatorId: string;
  isClosed?: boolean;
  missionUsers?: MissionUser[];
}

interface MissionFilesManagerProps {
  mission: Mission;
  currentUserId: string;
  currentPath?: string;
  onFileSelect?: (file: MissionFile) => void;
  selectedFileKey?: string;
}

export const MissionFilesManager: React.FC<MissionFilesManagerProps> = ({
  mission,
  currentUserId,
  currentPath = 'attachments',
  onFileSelect,
  selectedFileKey
}) => {
  const [files, setFiles] = useState<MissionFile[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [showNewFolder, setShowNewFolder] = useState(false);

  // Check user permissions
  const isCreator = mission.creatorId === currentUserId;
  const userRole = mission.missionUsers?.find(mu => mu.userId === currentUserId)?.role;
  const isGardien = userRole === 'gardien-temps' || userRole === 'gardien-parole' || userRole === 'gardien-memoire';
  const isClosed = mission.isClosed || false;
  const canManage = (isCreator || isGardien) && !isClosed; // Cannot manage if mission is closed

  const fetchFiles = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const url = `/api/missions/${mission.id}/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();
      // API returns { folders: [], files: [] } or { files: [] }
      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);
    }
  };

  useEffect(() => {
    if (!mission.id) return;
    fetchFiles();
  }, [mission.id, currentPath]);

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

    try {
      setIsUploading(true);
      const formData = new FormData();
      formData.append('file', file);
      formData.append('missionId', mission.id);
      formData.append('path', currentPath);

      const response = await fetch(`/api/missions/${mission.id}/files/upload`, {
        method: 'POST',
        body: formData
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        const errorMessage = errorData.details || errorData.error || 'Failed to upload file';
        throw new Error(errorMessage);
      }

      // Refresh file list
      await fetchFiles();
    } catch (err) {
      console.error('Error uploading file:', err);
      setError(err instanceof Error ? err.message : 'Failed to upload file');
    } finally {
      setIsUploading(false);
      // Reset input
      event.target.value = '';
    }
  };

  const handleCreateFolder = async () => {
    if (!newFolderName.trim() || !canManage) return;

    try {
      setIsLoading(true);
      const folderPath = currentPath ? `${currentPath}/${newFolderName}` : newFolderName;
      
      const response = await fetch(`/api/missions/${mission.id}/files/folder`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ path: folderPath })
      });

      if (!response.ok) {
        throw new Error('Failed to create folder');
      }

      // Refresh file list
      await fetchFiles();

      setNewFolderName('');
      setShowNewFolder(false);
    } catch (err) {
      console.error('Error creating folder:', err);
      setError(err instanceof Error ? err.message : 'Failed to create folder');
    } finally {
      setIsLoading(false);
    }
  };

  const handleDelete = async (file: MissionFile) => {
    if (!canManage || !confirm(`Êtes-vous sûr de vouloir supprimer ${file.name} ?`)) return;

    try {
      const response = await fetch(`/api/missions/${mission.id}/files`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ key: file.key })
      });

      if (!response.ok) {
        throw new Error('Failed to delete');
      }

      // Refresh file list
      await fetchFiles();
    } catch (err) {
      console.error('Error deleting file:', err);
      setError(err instanceof Error ? err.message : 'Failed to delete');
    }
  };

  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 justify-between mb-4">
          <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 || 'Fichiers'}
            </h2>
          </div>
          {canManage && (
            <div className="flex items-center space-x-2">
              <button
                onClick={() => setShowNewFolder(!showNewFolder)}
                className="p-2 text-carnet-text-primary hover:bg-carnet-hover rounded-md"
                title="Créer un dossier"
              >
                <FolderPlus className="h-5 w-5" />
              </button>
              <label className="p-2 text-carnet-text-primary hover:bg-carnet-hover rounded-md cursor-pointer">
                <Upload className="h-5 w-5" />
                <input
                  type="file"
                  className="hidden"
                  onChange={handleFileUpload}
                  disabled={isUploading}
                />
              </label>
            </div>
          )}
        </div>
        {showNewFolder && canManage && (
          <div className="flex items-center space-x-2">
            <input
              type="text"
              value={newFolderName}
              onChange={(e) => setNewFolderName(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleCreateFolder()}
              placeholder="Nom du dossier"
              className="flex-1 px-3 py-2 border border-carnet-border rounded-md text-sm text-carnet-text-primary bg-white focus:outline-none focus:ring-1 focus:ring-primary"
            />
            <button
              onClick={handleCreateFolder}
              className="px-4 py-2 bg-primary text-white rounded-md text-sm hover:bg-primary/90"
            >
              Créer
            </button>
            <button
              onClick={() => {
                setShowNewFolder(false);
                setNewFolderName('');
              }}
              className="px-4 py-2 border border-carnet-border rounded-md text-sm text-carnet-text-primary hover:bg-carnet-hover"
            >
              Annuler
            </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}
                  className={`p-4 hover:bg-carnet-hover flex items-center justify-between group ${
                    selectedFileKey === file.key ? 'bg-carnet-hover' : ''
                  }`}
                >
                  <div 
                    className="flex items-center space-x-2 flex-1 cursor-pointer"
                    onClick={() => onFileSelect?.(file)}
                  >
                    <Icon className="h-4 w-4 text-carnet-text-muted" />
                    <span className="text-sm text-carnet-text-primary">{file.name}</span>
                    {file.type === 'folder' && (
                      <ChevronRight className="h-4 w-4 text-carnet-text-muted" />
                    )}
                  </div>
                  {canManage && (
                    <button
                      onClick={() => handleDelete(file)}
                      className="p-2 text-red-500 hover:bg-red-50 rounded-md opacity-0 group-hover:opacity-100 transition-opacity"
                      title="Supprimer"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  )}
                </li>
              );
            })}
          </ul>
        )}
      </div>
      {isUploading && (
        <div className="p-4 border-t border-carnet-border">
          <div className="flex items-center space-x-2 text-carnet-text-muted">
            <Loader2 className="h-4 w-4 animate-spin" />
            <span className="text-sm">Upload en cours...</span>
          </div>
        </div>
      )}
    </div>
  );
};
