import React, { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { SearchInput } from '../ui/input';
import { FileNode } from '../../types';
import {
  LayoutGrid,
  List,
  Filter,
  MoreVertical,
  Download,
  Trash2,
  Folder,
  Music,
  Image as ImageIcon,
  File,
  CheckSquare,
  Square,
  Tag,
  ArrowUp,
  ArrowDown,
  Share2,
  Wand2,
  Stamp,
} from 'lucide-react';
import { useToast } from '../../context/ToastContext';
import { storageService } from '../../services/storageService';
import { AutoMetadataDetectionModal } from '../library/AutoMetadataDetectionModal';
import { WatermarkSettingsModal } from '../library/WatermarkSettingsModal';
import { FileDetailsView } from '../views/FileDetailsView';
import { LoadingState } from '../ui/LoadingState';
import { logger } from '@/utils/logger';

type SortField = 'name' | 'size' | 'modified' | 'type';
type SortOrder = 'asc' | 'desc';

export const CloudFileBrowser: React.FC = () => {
  const { addToast } = useToast();
  const [viewMode, setViewMode] = useState<'list' | 'grid'>('list');
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedFiles, setSelectedFiles] = useState<string[]>([]);
  const [_currentFolder, setCurrentFolder] = useState('Root');
  const [files, setFiles] = useState<(FileNode & { tags?: string[] })[]>([]);
  const [loading, setLoading] = useState(true);

  // Navigation State
  const [selectedFileId, setSelectedFileId] = useState<string | null>(null);

  // Sorting & Filtering
  const [sortField, setSortField] = useState<SortField>('modified');
  const [sortOrder, setSortOrder] = useState<SortOrder>('desc');
  const [activeTags, setActiveTags] = useState<string[]>([]);
  const [availableTags] = useState([
    'Vocals',
    'Bass',
    'Drums',
    'Project',
    'Art',
    'Legal',
    'Reference',
    'Stem',
    'Raw',
  ]);

  // Modals
  const [showMetadataModal, setShowMetadataModal] = useState(false);
  const [showWatermarkModal, setShowWatermarkModal] = useState(false);

  useEffect(() => {
    const loadFiles = async () => {
      setLoading(true);
      try {
        const data = await storageService.listFiles();
        setFiles(data);
      } catch (e) {
        logger.error('Error loading files', {
          error: e instanceof Error ? e.message : String(e),
          stack: e instanceof Error ? e.stack : undefined,
        });
      } finally {
        setLoading(false);
      }
    };
    loadFiles();
  }, []);

  const handleSort = (field: SortField) => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortOrder('asc');
    }
  };

  const toggleTag = (tag: string) => {
    setActiveTags((prev) =>
      prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag],
    );
  };

  const toggleSelection = (id: string) => {
    setSelectedFiles((prev) =>
      prev.includes(id) ? prev.filter((fid) => fid !== id) : [...prev, id],
    );
  };

  const selectAll = () => {
    if (selectedFiles.length === files.length) setSelectedFiles([]);
    else setSelectedFiles(files.map((f) => f.id));
  };

  const handleFileClick = (file: FileNode) => {
    if (file.type === 'folder') {
      setCurrentFolder(file.name);
      addToast(`Navigated to ${file.name}`, 'info');
    } else {
      setSelectedFileId(file.id);
    }
  };

  const filteredFiles = files
    .filter((f) => f.name.toLowerCase().includes(searchQuery.toLowerCase()))
    .filter(
      (f) =>
        activeTags.length === 0 || f.tags?.some((t) => activeTags.includes(t)),
    )
    .sort((a, b) => {
      let valA: string | number = a[sortField] || '';
      let valB: string | number = b[sortField] || '';
      if (sortField === 'size') {
        // Mock size parsing for sort
        valA = parseInt(a.size || '0') || 0;
        valB = parseInt(b.size || '0') || 0;
      }
      if (valA < valB) return sortOrder === 'asc' ? -1 : 1;
      if (valA > valB) return sortOrder === 'asc' ? 1 : -1;
      return 0;
    });

  const handleAction = (action: string) => {
    if (selectedFiles.length === 0) return;
    addToast(`${action} ${selectedFiles.length} items`, 'success');
    setSelectedFiles([]);
  };

  if (selectedFileId) {
    return (
      <FileDetailsView
        fileId={selectedFileId}
        onBack={() => setSelectedFileId(null)}
      />
    );
  }

  // CRITIQUE FIX #20: Utiliser LoadingState standardisé pour cohérence UX
  if (loading) {
    return (
      <LoadingState
        isLoading={true}
        variant="spinner"
        text="Chargement des fichiers..."
        className="py-20"
      />
    );
  }

  return (
    <div className="space-y-6 h-full flex flex-col">
      {/* Controls Bar */}
      <div className="flex flex-col xl:flex-row gap-4 justify-between items-start xl:items-center bg-kodo-ink/50 p-4 rounded-xl border border-kodo-steel/50">
        <div className="flex flex-col sm:flex-row gap-4 w-full xl:w-auto">
          <div className="w-full sm:w-64">
            <SearchInput
              placeholder="Search files..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>

          {/* Tag Filter */}
          <div className="flex items-center gap-2 overflow-x-auto no-scrollbar pb-2 sm:pb-0">
            <Filter className="w-4 h-4 text-kodo-content-dim shrink-0" />
            {availableTags.slice(0, 5).map((tag) => (
              <button
                key={tag}
                onClick={() => toggleTag(tag)}
                className={`px-2 py-1 rounded text-xs border transition-colors whitespace-nowrap ${activeTags.includes(tag) ? 'bg-kodo-cyan/20 border-kodo-cyan text-kodo-cyan' : 'border-kodo-steel text-kodo-content-dim hover:border-kodo-steel'}`}
              >
                {tag}
              </button>
            ))}
          </div>
        </div>

        <div className="flex gap-2 w-full xl:w-auto justify-between xl:justify-end">
          {selectedFiles.length > 0 && (
            <div className="flex gap-2 mr-2 animate-fadeIn">
              <Button
                variant="ghost"
                size="icon"
                onClick={() => handleAction('Downloaded')}
                title="Download"
                aria-label="Télécharger"
              >
                <Download className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => handleAction('Tagged')}
                title="Add Tag"
                aria-label="Ajouter un tag"
              >
                <Tag className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => handleAction('Deleted')}
                className="text-kodo-red hover:bg-kodo-red/10"
                aria-label="Supprimer"
              >
                <Trash2 className="w-4 h-4" />
              </Button>
            </div>
          )}

          <div className="flex gap-2">
            <Button
              variant="ghost"
              onClick={() => setShowMetadataModal(true)}
              title="AI Auto-Tag"
              aria-label="AI Auto-Tag"
            >
              <Wand2 className="w-4 h-4" />
            </Button>
            <Button
              variant="ghost"
              onClick={() => setShowWatermarkModal(true)}
              title="Watermark Settings"
              aria-label="Paramètres de filigrane"
            >
              <Stamp className="w-4 h-4" />
            </Button>
            <div className="bg-kodo-void rounded-lg p-1 border border-kodo-steel flex items-center">
              <span className="text-xs text-kodo-content-dim px-2 uppercase font-bold">
                Sort:
              </span>
              <select
                className="bg-transparent text-xs text-white outline-none"
                value={sortField}
                onChange={(e) => setSortField(e.target.value as SortField)}
              >
                <option value="modified">Date</option>
                <option value="name">Name</option>
                <option value="size">Size</option>
                <option value="type">Type</option>
              </select>
              <button
                onClick={() =>
                  setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
                }
                className="ml-2 p-1 hover:text-white text-kodo-content-dim"
              >
                {sortOrder === 'asc' ? (
                  <ArrowUp className="w-3 h-3" />
                ) : (
                  <ArrowDown className="w-3 h-3" />
                )}
              </button>
            </div>

            <div className="bg-kodo-void p-1 rounded-lg border border-kodo-steel flex">
              <button
                onClick={() => setViewMode('list')}
                className={`p-2 rounded ${viewMode === 'list' ? 'bg-kodo-slate text-white' : 'text-kodo-content-dim hover:text-white'}`}
              >
                <List className="w-4 h-4" />
              </button>
              <button
                onClick={() => setViewMode('grid')}
                className={`p-2 rounded ${viewMode === 'grid' ? 'bg-kodo-slate text-white' : 'text-kodo-content-dim hover:text-white'}`}
              >
                <LayoutGrid className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* File Content */}
      <div className="flex-1 overflow-y-auto custom-scrollbar min-h-[400px]">
        {viewMode === 'list' ? (
          <div className="bg-kodo-graphite border border-kodo-steel rounded-xl overflow-hidden">
            <table className="w-full text-left border-collapse">
              <thead className="bg-kodo-ink text-xs font-mono text-kodo-content-dim uppercase tracking-wider sticky top-0 z-10">
                <tr>
                  <th className="p-4 w-10">
                    <div
                      onClick={selectAll}
                      className="cursor-pointer hover:text-white"
                    >
                      {selectedFiles.length === files.length &&
                      files.length > 0 ? (
                        <CheckSquare className="w-4 h-4 text-kodo-cyan" />
                      ) : (
                        <Square className="w-4 h-4" />
                      )}
                    </div>
                  </th>
                  <th
                    className="p-4 cursor-pointer hover:text-white"
                    onClick={() => handleSort('name')}
                  >
                    Name
                  </th>
                  <th className="p-4">Tags</th>
                  <th
                    className="p-4 cursor-pointer hover:text-white"
                    onClick={() => handleSort('size')}
                  >
                    Size
                  </th>
                  <th
                    className="p-4 cursor-pointer hover:text-white"
                    onClick={() => handleSort('modified')}
                  >
                    Modified
                  </th>
                  <th className="p-4 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-kodo-steel/30 text-sm">
                {filteredFiles.map((file) => (
                  <tr
                    key={file.id}
                    className={`group hover:bg-white/5 transition-colors ${selectedFiles.includes(file.id) ? 'bg-kodo-cyan/5' : ''}`}
                  >
                    <td className="p-4">
                      <div
                        onClick={() => toggleSelection(file.id)}
                        className="cursor-pointer text-kodo-content-dim hover:text-white"
                      >
                        {selectedFiles.includes(file.id) ? (
                          <CheckSquare className="w-4 h-4 text-kodo-cyan" />
                        ) : (
                          <Square className="w-4 h-4" />
                        )}
                      </div>
                    </td>
                    <td className="p-4">
                      <div
                        className="flex items-center gap-3 cursor-pointer"
                        onClick={() => handleFileClick(file)}
                      >
                        {file.type === 'folder' && (
                          <Folder className="w-5 h-5 text-kodo-gold" />
                        )}
                        {file.type === 'audio' && (
                          <Music className="w-5 h-5 text-kodo-cyan" />
                        )}
                        {file.type === 'image' && (
                          <ImageIcon className="w-5 h-5 text-kodo-magenta" />
                        )}
                        {['document', 'archive', 'project'].includes(
                          file.type,
                        ) && <File className="w-5 h-5 text-kodo-content-dim" />}
                        <span className="font-medium text-kodo-text-main group-hover:text-white transition-colors">
                          {file.name}
                        </span>
                      </div>
                    </td>
                    <td className="p-4">
                      <div className="flex gap-1">
                        {file.tags?.map((t) => (
                          <span
                            key={t}
                            className="text-[10px] bg-kodo-slate px-1.5 py-0.5 rounded text-kodo-content-dim border border-kodo-steel"
                          >
                            {t}
                          </span>
                        ))}
                      </div>
                    </td>
                    <td className="p-4 text-kodo-content-dim font-mono text-xs">
                      {file.size}
                    </td>
                    <td className="p-4 text-kodo-content-dim text-xs">
                      {file.modified}
                    </td>
                    <td className="p-4 text-right">
                      <div className="flex justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                        {file.type === 'audio' && (
                          <button
                            className="p-1.5 hover:bg-white/10 rounded text-kodo-cyan"
                            title="Process with AI"
                            onClick={() => addToast('Sent to AI Tools')}
                          >
                            <Wand2 className="w-4 h-4" />
                          </button>
                        )}
                        <button className="p-1.5 hover:bg-white/10 rounded text-kodo-content-dim hover:text-white">
                          <Share2 className="w-4 h-4" />
                        </button>
                        <button className="p-1.5 hover:bg-white/10 rounded text-kodo-content-dim hover:text-white">
                          <MoreVertical className="w-4 h-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4">
            {filteredFiles.map((file) => (
              <Card
                key={file.id}
                variant="default"
                className={`p-4 flex flex-col items-center text-center gap-3 cursor-pointer hover:border-kodo-cyan/50 transition-all group relative ${selectedFiles.includes(file.id) ? 'border-kodo-cyan bg-kodo-cyan/5' : ''}`}
                onClick={() => handleFileClick(file)}
              >
                <div
                  className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
                  onClick={(e) => {
                    e.stopPropagation();
                    toggleSelection(file.id);
                  }}
                >
                  {selectedFiles.includes(file.id) ? (
                    <CheckSquare className="w-4 h-4 text-kodo-cyan" />
                  ) : (
                    <Square className="w-4 h-4 text-kodo-content-dim hover:text-white" />
                  )}
                </div>

                <div className="w-16 h-16 rounded-2xl bg-kodo-ink flex items-center justify-center shadow-lg group-hover:scale-110 transition-transform duration-300">
                  {file.type === 'folder' && (
                    <Folder className="w-8 h-8 text-kodo-gold" />
                  )}
                  {file.type === 'audio' && (
                    <Music className="w-8 h-8 text-kodo-cyan" />
                  )}
                  {file.type === 'image' && (
                    <ImageIcon className="w-8 h-8 text-kodo-magenta" />
                  )}
                  {['document', 'archive', 'project'].includes(file.type) && (
                    <File className="w-8 h-8 text-kodo-content-dim" />
                  )}
                </div>
                <div className="w-full">
                  <h4
                    className="font-bold text-white text-sm truncate w-full"
                    title={file.name}
                  >
                    {file.name}
                  </h4>
                  <div className="flex justify-center gap-1 mt-1 flex-wrap">
                    {file.tags?.slice(0, 2).map((t) => (
                      <span
                        key={t}
                        className="text-[8px] bg-white/10 px-1 rounded text-kodo-content-dim"
                      >
                        {t}
                      </span>
                    ))}
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Modals */}
      {showMetadataModal && (
        <AutoMetadataDetectionModal
          fileName={
            selectedFileId
              ? files.find((f) => f.id === selectedFileId)?.name ||
                'Selected File'
              : 'Scan Library'
          }
          onClose={() => setShowMetadataModal(false)}
          onApply={(data) => {
            addToast(`Applied: ${data.genre} - ${data.bpm}BPM`, 'success');
            setShowMetadataModal(false);
          }}
        />
      )}
      {showWatermarkModal && (
        <WatermarkSettingsModal
          onClose={() => setShowWatermarkModal(false)}
          onSave={() => addToast('Watermark settings updated', 'success')}
        />
      )}
    </div>
  );
};
