'use client';

import { useState } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { ProjectFolder, ProjectFile, FileType } from '@/lib/types';
import { mockUsers } from '@/lib/mock-data';
import { 
  Plus, 
  Folder, 
  File, 
  Link, 
  FileText, 
  Download, 
  Eye, 
  Edit, 
  Trash2,
  Upload,
  FolderPlus,
  MoreHorizontal,
  Search,
  Calendar,
  User,
  ExternalLink,
  FileImage,
  FileSpreadsheet,
  FileCode,
  Archive
} from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';

interface DocsAndFilesProps {
  projectId: string;
}

// Enhanced mock data with more realistic content
const mockFolders: ProjectFolder[] = [
  {
    id: '1',
    name: 'Requirements',
    description: 'Project requirements and specifications',
    children: [
      {
        id: '1.1',
        name: 'Functional Requirements',
        parentId: '1',
        children: [],
        files: [
          {
            id: 'f1',
            name: 'User Stories.docx',
            type: 'file',
            size: 245760,
            mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            folderId: '1.1',
            uploadedBy: '1',
            uploadedAt: new Date('2024-01-15')
          }
        ],
        createdBy: '1',
        createdAt: new Date('2024-01-15')
      }
    ],
    files: [
      {
        id: 'f2',
        name: 'Project Charter.pdf',
        type: 'file',
        size: 1024000,
        mimeType: 'application/pdf',
        folderId: '1',
        uploadedBy: '1',
        uploadedAt: new Date('2024-01-10')
      }
    ],
    createdBy: '1',
    createdAt: new Date('2024-01-10')
  },
  {
    id: '2',
    name: 'Design',
    description: 'UI/UX designs and mockups',
    children: [],
    files: [
      {
        id: 'f3',
        name: 'Figma Design System',
        type: 'url',
        url: 'https://figma.com/design-system',
        description: 'Complete design system with components and guidelines',
        folderId: '2',
        uploadedBy: '4',
        uploadedAt: new Date('2024-01-20')
      },
      {
        id: 'f4',
        name: 'Wireframes.sketch',
        type: 'file',
        size: 5120000,
        mimeType: 'application/sketch',
        folderId: '2',
        uploadedBy: '4',
        uploadedAt: new Date('2024-01-18')
      }
    ],
    createdBy: '4',
    createdAt: new Date('2024-01-18')
  }
];

const mockFiles: ProjectFile[] = [
  {
    id: 'f5',
    name: 'Meeting Notes - Week 1',
    type: 'note',
    content: 'Project kickoff meeting notes:\n\n1. Discussed project scope and timeline\n2. Assigned team roles and responsibilities\n3. Set up communication channels\n4. Next meeting scheduled for next week',
    description: 'Weekly team meeting notes',
    uploadedBy: '2',
    uploadedAt: new Date('2024-01-22')
  },
  {
    id: 'f6',
    name: 'API Documentation',
    type: 'url',
    url: 'https://api-docs.example.com',
    description: 'Complete API documentation with endpoints and examples',
    uploadedBy: '3',
    uploadedAt: new Date('2024-02-01')
  }
];

export function DocsAndFiles({ projectId }: DocsAndFilesProps) {
  const [folders, setFolders] = useState<ProjectFolder[]>(mockFolders);
  const [files, setFiles] = useState<ProjectFile[]>(mockFiles);
  const [currentFolder, setCurrentFolder] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [createType, setCreateType] = useState<'folder' | 'file' | 'url' | 'note'>('file');
  const [newItem, setNewItem] = useState({
    name: '',
    description: '',
    url: '',
    content: ''
  });

  const getUserName = (userId: string) => {
    const user = mockUsers.find(u => u.id === userId);
    return user ? user.name : 'Unknown User';
  };

  const getInitials = (name: string) => {
    return name.split(' ').map(n => n[0]).join('').toUpperCase();
  };

  const formatFileSize = (bytes: number) => {
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    if (bytes === 0) return '0 Bytes';
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
  };

  const formatDate = (date: Date) => {
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
  };

  const getFileIcon = (file: ProjectFile) => {
    if (file.type === 'url') return ExternalLink;
    if (file.type === 'note') return FileText;
    
    if (file.mimeType) {
      if (file.mimeType.includes('image')) return FileImage;
      if (file.mimeType.includes('spreadsheet') || file.mimeType.includes('excel')) return FileSpreadsheet;
      if (file.mimeType.includes('code') || file.mimeType.includes('javascript')) return FileCode;
      if (file.mimeType.includes('pdf')) return File;
    }
    
    return File;
  };

  const getFileIconColor = (file: ProjectFile) => {
    if (file.type === 'url') return 'text-primary';
    if (file.type === 'note') return 'text-green-600';
    
    if (file.mimeType) {
      if (file.mimeType.includes('image')) return 'text-primary';
      if (file.mimeType.includes('spreadsheet') || file.mimeType.includes('excel')) return 'text-emerald-600';
      if (file.mimeType.includes('code') || file.mimeType.includes('javascript')) return 'text-orange-600';
      if (file.mimeType.includes('pdf')) return 'text-red-600';
    }
    
    return 'text-muted-foreground';
  };

  const getCurrentFolderData = () => {
    if (!currentFolder) return null;
    
    const findFolder = (folders: ProjectFolder[], id: string): ProjectFolder | null => {
      for (const folder of folders) {
        if (folder.id === id) return folder;
        const found = findFolder(folder.children, id);
        if (found) return found;
      }
      return null;
    };
    
    return findFolder(folders, currentFolder);
  };

  const getDisplayItems = () => {
    const currentFolderData = getCurrentFolderData();
    const displayFolders = currentFolderData ? currentFolderData.children : folders;
    const displayFiles = currentFolderData ? currentFolderData.files : files;
    
    const filteredFolders = displayFolders.filter(folder =>
      folder.name.toLowerCase().includes(searchTerm.toLowerCase())
    );
    
    const filteredFiles = displayFiles.filter(file =>
      file.name.toLowerCase().includes(searchTerm.toLowerCase())
    );
    
    return { folders: filteredFolders, files: filteredFiles };
  };

  const handleCreateItem = () => {
    if (createType === 'folder') {
      const newFolder: ProjectFolder = {
        id: Date.now().toString(),
        name: newItem.name,
        description: newItem.description,
        parentId: currentFolder || undefined,
        children: [],
        files: [],
        createdBy: '1', // Current user
        createdAt: new Date()
      };
      
      if (currentFolder) {
        // Add to current folder
        const updateFolders = (folders: ProjectFolder[]): ProjectFolder[] => {
          return folders.map(folder => {
            if (folder.id === currentFolder) {
              return { ...folder, children: [...folder.children, newFolder] };
            }
            return { ...folder, children: updateFolders(folder.children) };
          });
        };
        setFolders(updateFolders(folders));
      } else {
        setFolders([...folders, newFolder]);
      }
    } else {
      const newFile: ProjectFile = {
        id: Date.now().toString(),
        name: newItem.name,
        type: createType as FileType,
        url: createType === 'url' ? newItem.url : undefined,
        content: createType === 'note' ? newItem.content : undefined,
        description: newItem.description,
        folderId: currentFolder || undefined,
        uploadedBy: '1', // Current user
        uploadedAt: new Date()
      };
      
      if (currentFolder) {
        // Add to current folder
        const updateFolders = (folders: ProjectFolder[]): ProjectFolder[] => {
          return folders.map(folder => {
            if (folder.id === currentFolder) {
              return { ...folder, files: [...folder.files, newFile] };
            }
            return { ...folder, children: updateFolders(folder.children) };
          });
        };
        setFolders(updateFolders(folders));
      } else {
        setFiles([...files, newFile]);
      }
    }
    
    setNewItem({ name: '', description: '', url: '', content: '' });
    setIsCreateDialogOpen(false);
  };

  const { folders: displayFolders, files: displayFiles } = getDisplayItems();
  const currentFolderData = getCurrentFolderData();
  const totalItems = displayFolders.length + displayFiles.length;

  return (
    <div className="space-y-6">
      {/* Header with Stats */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-4">
          <div>
            <h4 className="text-lg font-semibold text-foreground">
              {currentFolderData ? currentFolderData.name : 'All Files'}
            </h4>
            <p className="text-sm text-muted-foreground">
              {totalItems} {totalItems === 1 ? 'item' : 'items'} • 
              {displayFolders.length} {displayFolders.length === 1 ? 'folder' : 'folders'}, 
              {displayFiles.length} {displayFiles.length === 1 ? 'file' : 'files'}
            </p>
          </div>
        </div>
        
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button size="sm" className="bg-primary hover:bg-primary">
                <Plus className="h-4 w-4 mr-2" />
                Add New
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DialogTrigger asChild>
                <DropdownMenuItem onClick={() => setCreateType('folder')}>
                  <FolderPlus className="h-4 w-4 mr-2" />
                  New Folder
                </DropdownMenuItem>
              </DialogTrigger>
              <DialogTrigger asChild>
                <DropdownMenuItem onClick={() => setCreateType('file')}>
                  <Upload className="h-4 w-4 mr-2" />
                  Upload File
                </DropdownMenuItem>
              </DialogTrigger>
              <DialogTrigger asChild>
                <DropdownMenuItem onClick={() => setCreateType('url')}>
                  <Link className="h-4 w-4 mr-2" />
                  Add URL
                </DropdownMenuItem>
              </DialogTrigger>
              <DialogTrigger asChild>
                <DropdownMenuItem onClick={() => setCreateType('note')}>
                  <FileText className="h-4 w-4 mr-2" />
                  Create Note
                </DropdownMenuItem>
              </DialogTrigger>
            </DropdownMenuContent>
          </DropdownMenu>
          
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>
                {createType === 'folder' && 'Create New Folder'}
                {createType === 'file' && 'Upload File'}
                {createType === 'url' && 'Add URL'}
                {createType === 'note' && 'Create Note'}
              </DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="name">
                  {createType === 'folder' ? 'Folder Name' : 'Name'}
                </Label>
                <Input
                  id="name"
                  value={newItem.name}
                  onChange={(e) => setNewItem(prev => ({ ...prev, name: e.target.value }))}
                  placeholder={`Enter ${createType === 'folder' ? 'folder' : 'item'} name`}
                />
              </div>
              
              {createType === 'url' && (
                <div className="space-y-2">
                  <Label htmlFor="url">URL</Label>
                  <Input
                    id="url"
                    type="url"
                    value={newItem.url}
                    onChange={(e) => setNewItem(prev => ({ ...prev, url: e.target.value }))}
                    placeholder="https://example.com"
                  />
                </div>
              )}
              
              {createType === 'note' && (
                <div className="space-y-2">
                  <Label htmlFor="content">Content</Label>
                  <Textarea
                    id="content"
                    value={newItem.content}
                    onChange={(e) => setNewItem(prev => ({ ...prev, content: e.target.value }))}
                    placeholder="Enter note content..."
                    rows={6}
                  />
                </div>
              )}
              
              {createType === 'file' && (
                <div className="space-y-2">
                  <Label htmlFor="file">File</Label>
                  <div className="border-2 border-dashed border-border rounded-lg p-8 text-center hover:border-primary/40 transition-colors">
                    <Upload className="h-10 w-10 text-muted-foreground mx-auto mb-3" />
                    <p className="text-sm text-muted-foreground mb-2">
                      <span className="font-medium">Click to upload</span> or drag and drop
                    </p>
                    <p className="text-xs text-muted-foreground">
                      PDF, DOC, XLS, PNG, JPG up to 10MB
                    </p>
                    <Input type="file" className="hidden" />
                  </div>
                </div>
              )}
              
              <div className="space-y-2">
                <Label htmlFor="description">Description (Optional)</Label>
                <Textarea
                  id="description"
                  value={newItem.description}
                  onChange={(e) => setNewItem(prev => ({ ...prev, description: e.target.value }))}
                  placeholder="Enter description..."
                  rows={3}
                />
              </div>
              
              <div className="flex justify-end space-x-2">
                <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                  Cancel
                </Button>
                <Button onClick={handleCreateItem}>
                  {createType === 'folder' && 'Create Folder'}
                  {createType === 'file' && 'Upload File'}
                  {createType === 'url' && 'Add URL'}
                  {createType === 'note' && 'Create Note'}
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Breadcrumb */}
      {currentFolder && (
        <div className="flex items-center space-x-2 text-sm">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setCurrentFolder(null)}
            className="p-0 h-auto font-normal text-primary hover:text-primary"
          >
            All Files
          </Button>
          <span className="text-muted-foreground">/</span>
          <span className="font-medium text-foreground">{currentFolderData?.name}</span>
        </div>
      )}

      {/* Search */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
        <Input
          placeholder="Search files and folders..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="pl-10 bg-muted/50 border-border focus:bg-card"
        />
      </div>

      {/* Content Grid */}
      <div className="space-y-4">
        {/* Folders */}
        {displayFolders.length > 0 && (
          <div>
            <h5 className="text-sm font-medium text-foreground/80 mb-3 flex items-center">
              <Folder className="h-4 w-4 mr-2" />
              Folders ({displayFolders.length})
            </h5>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {displayFolders.map((folder) => (
                <Card
                  key={folder.id}
                  className="p-4 hover:shadow-md transition-all duration-200 cursor-pointer border-l-4 border-l-blue-500 bg-gradient-to-r from-primary/10 to-white"
                  onClick={() => setCurrentFolder(folder.id)}
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex items-center space-x-3 flex-1 min-w-0">
                      <div className="p-2 bg-primary/15 rounded-lg">
                        <Folder className="h-5 w-5 text-primary" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h4 className="font-semibold text-foreground truncate">{folder.name}</h4>
                        {folder.description && (
                          <p className="text-sm text-muted-foreground truncate mt-1">{folder.description}</p>
                        )}
                      </div>
                    </div>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
                        <Button variant="ghost" size="sm" className="h-8 w-8 p-0 opacity-0 group-hover:opacity-100">
                          <MoreHorizontal className="h-4 w-4" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem>
                          <Edit className="h-4 w-4 mr-2" />
                          Rename
                        </DropdownMenuItem>
                        <DropdownMenuItem className="text-red-600">
                          <Trash2 className="h-4 w-4 mr-2" />
                          Delete
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                  
                  <div className="flex items-center justify-between text-xs text-muted-foreground">
                    <div className="flex items-center space-x-1">
                      <Archive className="h-3 w-3" />
                      <span>{folder.children.length + folder.files.length} items</span>
                    </div>
                    <div className="flex items-center space-x-1">
                      <Calendar className="h-3 w-3" />
                      <span>{formatDate(folder.createdAt)}</span>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          </div>
        )}

        {/* Files */}
        {displayFiles.length > 0 && (
          <div>
            <h5 className="text-sm font-medium text-foreground/80 mb-3 flex items-center">
              <File className="h-4 w-4 mr-2" />
              Files ({displayFiles.length})
            </h5>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {displayFiles.map((file) => {
                const FileIcon = getFileIcon(file);
                const iconColor = getFileIconColor(file);
                return (
                  <Card key={file.id} className="p-4 hover:shadow-md transition-all duration-200 group">
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center space-x-3 flex-1 min-w-0">
                        <div className="p-2 bg-muted/50 rounded-lg">
                          <FileIcon className={`h-5 w-5 ${iconColor}`} />
                        </div>
                        <div className="flex-1 min-w-0">
                          <h4 className="font-semibold text-foreground truncate">{file.name}</h4>
                          {file.description && (
                            <p className="text-sm text-muted-foreground truncate mt-1">{file.description}</p>
                          )}
                        </div>
                      </div>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="sm" className="h-8 w-8 p-0 opacity-0 group-hover:opacity-100">
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem>
                            <Eye className="h-4 w-4 mr-2" />
                            View
                          </DropdownMenuItem>
                          {file.type === 'file' && (
                            <DropdownMenuItem>
                              <Download className="h-4 w-4 mr-2" />
                              Download
                            </DropdownMenuItem>
                          )}
                          {file.type === 'url' && (
                            <DropdownMenuItem>
                              <ExternalLink className="h-4 w-4 mr-2" />
                              Open Link
                            </DropdownMenuItem>
                          )}
                          <DropdownMenuItem>
                            <Edit className="h-4 w-4 mr-2" />
                            Edit
                          </DropdownMenuItem>
                          <DropdownMenuItem className="text-red-600">
                            <Trash2 className="h-4 w-4 mr-2" />
                            Delete
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </div>
                    
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <Badge variant="outline" className="text-xs">
                          {file.type.toUpperCase()}
                        </Badge>
                        {file.size && (
                          <span className="text-xs text-muted-foreground">{formatFileSize(file.size)}</span>
                        )}
                      </div>
                      
                      <div className="flex items-center justify-between text-xs text-muted-foreground">
                        <div className="flex items-center space-x-1">
                          <div className="h-4 w-4 rounded-full bg-primary/15 flex items-center justify-center">
                            <span className="text-xs font-medium text-primary">
                              {getInitials(getUserName(file.uploadedBy))}
                            </span>
                          </div>
                          <span>{getUserName(file.uploadedBy)}</span>
                        </div>
                        <div className="flex items-center space-x-1">
                          <Calendar className="h-3 w-3" />
                          <span>{formatDate(file.uploadedAt)}</span>
                        </div>
                      </div>
                    </div>
                  </Card>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* Empty State */}
      {displayFolders.length === 0 && displayFiles.length === 0 && (
        <div className="text-center py-12">
          <div className="mx-auto w-24 h-24 bg-muted rounded-full flex items-center justify-center mb-4">
            {searchTerm ? (
              <Search className="h-8 w-8 text-muted-foreground" />
            ) : (
              <Folder className="h-8 w-8 text-muted-foreground" />
            )}
          </div>
          <h4 className="text-lg font-semibold text-foreground mb-2">
            {searchTerm ? 'No results found' : 'No files or folders'}
          </h4>
          <p className="text-muted-foreground mb-6 max-w-sm mx-auto">
            {searchTerm 
              ? `No items match "${searchTerm}". Try adjusting your search terms.`
              : 'Get started by creating a folder or uploading your first file.'
            }
          </p>
          {!searchTerm && (
            <Button onClick={() => setIsCreateDialogOpen(true)} className="bg-primary hover:bg-primary">
              <Plus className="h-4 w-4 mr-2" />
              Add First Item
            </Button>
          )}
        </div>
      )}
    </div>
  );
}