'use client';

import { useTranslations } from 'next-intl';
import { formatDistanceToNow } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  Cloud,
  FileText,
  FileImage,
  FileSpreadsheet,
  FileVideo,
  FileArchive,
  Folder,
  Download,
  ExternalLink,
} from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { WidgetContainer } from '../../widget-container';
import { useRecentFiles, formatFileSize } from '@/hooks/integrations';
import type { NextcloudFile } from '@/types/integrations';

interface FilesWidgetProps {
  id: string;
  isEditing?: boolean;
  onRemove?: () => void;
  locale?: string;
  maxItems?: number;
  className?: string;
}

/**
 * Get file icon based on mime type
 */
function getFileIcon(file: NextcloudFile) {
  if (file.type === 'folder') return Folder;

  const mimeType = file.mimeType || '';
  if (mimeType.startsWith('image/')) return FileImage;
  if (mimeType.startsWith('video/')) return FileVideo;
  if (mimeType.includes('spreadsheet') || mimeType.includes('excel')) return FileSpreadsheet;
  if (mimeType.includes('zip') || mimeType.includes('compressed')) return FileArchive;
  return FileText;
}

/**
 * Get file icon color based on type
 */
function getFileColor(file: NextcloudFile): string {
  if (file.type === 'folder') return 'text-yellow-500';

  const mimeType = file.mimeType || '';
  if (mimeType.startsWith('image/')) return 'text-green-500';
  if (mimeType.startsWith('video/')) return 'text-purple-500';
  if (mimeType.includes('spreadsheet') || mimeType.includes('excel')) return 'text-emerald-500';
  if (mimeType.includes('pdf')) return 'text-red-500';
  if (mimeType.includes('zip') || mimeType.includes('compressed')) return 'text-orange-500';
  return 'text-blue-500';
}

/**
 * Files Widget - Displays recent Nextcloud files
 */
export function FilesWidget({
  id,
  isEditing = false,
  onRemove,
  locale = 'de',
  maxItems = 5,
  className,
}: FilesWidgetProps) {
  const t = useTranslations('widgets.files');
  const { data: files, isLoading } = useRecentFiles(maxItems);
  const dateLocale = locale === 'de' ? de : enUS;

  return (
    <WidgetContainer
      id={id}
      title={t('name')}
      icon={<Cloud className="h-4 w-4 text-primary" />}
      isEditing={isEditing}
      onRemove={onRemove}
      className={className}
    >
      <ScrollArea className="h-[220px] pr-2">
        {isLoading ? (
          <div className="space-y-3">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="flex items-center gap-3">
                <Skeleton className="h-10 w-10 rounded" />
                <div className="flex-1 space-y-2">
                  <Skeleton className="h-4 w-3/4" />
                  <Skeleton className="h-3 w-1/2" />
                </div>
              </div>
            ))}
          </div>
        ) : files && files.length > 0 ? (
          <div className="space-y-2">
            {files.map((file, index) => {
              const Icon = getFileIcon(file);
              const iconColor = getFileColor(file);

              return (
                <motion.div
                  key={file.id}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.2, delay: index * 0.05 }}
                  className="flex items-center gap-3 rounded-lg border p-2 transition-colors hover:bg-muted/50"
                >
                  <div
                    className={cn(
                      'flex h-10 w-10 items-center justify-center rounded-lg bg-muted',
                      iconColor
                    )}
                  >
                    <Icon className="h-5 w-5" />
                  </div>

                  <div className="min-w-0 flex-1">
                    <p className="truncate text-sm font-medium">{file.name}</p>
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <span>{formatFileSize(file.size)}</span>
                      <span>-</span>
                      <span>
                        {formatDistanceToNow(file.modifiedAt, {
                          addSuffix: true,
                          locale: dateLocale,
                        })}
                      </span>
                    </div>
                    <p className="truncate text-xs text-muted-foreground">{file.path}</p>
                  </div>

                  {file.downloadUrl && (
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 shrink-0"
                          asChild
                        >
                          <a href={file.downloadUrl} download>
                            <Download className="h-4 w-4" />
                          </a>
                        </Button>
                      </TooltipTrigger>
                      <TooltipContent>{t('download')}</TooltipContent>
                    </Tooltip>
                  )}
                </motion.div>
              );
            })}
          </div>
        ) : (
          <div className="flex h-full items-center justify-center text-sm text-muted-foreground">
            {t('noFiles')}
          </div>
        )}
      </ScrollArea>

      {/* Footer link */}
      <div className="mt-3 border-t pt-3">
        <Button variant="ghost" size="sm" className="w-full" asChild>
          <Link href={`/${locale}/integrations/nextcloud`}>
            <ExternalLink className="mr-2 h-4 w-4" />
            {t('openNextcloud')}
          </Link>
        </Button>
      </div>
    </WidgetContainer>
  );
}
