'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 {
  Cloud,
  FileText,
  FileImage,
  FileSpreadsheet,
  FileVideo,
  FileArchive,
  Folder,
  Download,
  HardDrive,
  Clock,
} from 'lucide-react';

import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useFiles, useRecentFiles, formatFileSize } from '@/hooks/integrations';
import type { NextcloudFile } from '@/types/integrations';

interface NextcloudContentProps {
  locale: 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 bg-yellow-500/10';

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

/**
 * Nextcloud integration content - displays files
 */
export function NextcloudContent({ locale }: NextcloudContentProps) {
  const t = useTranslations('widgets.files');
  const { data: files, isLoading: filesLoading } = useFiles();
  const { data: recentFiles, isLoading: recentLoading } = useRecentFiles(10);
  const dateLocale = locale === 'de' ? de : enUS;

  const totalSize = files?.reduce((sum, f) => sum + f.size, 0) ?? 0;
  const folderCount = files?.filter((f) => f.type === 'folder').length ?? 0;
  const fileCount = files?.filter((f) => f.type === 'file').length ?? 0;

  return (
    <div className="space-y-6">
      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Dateien</CardTitle>
            <FileText className="h-4 w-4 text-primary" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {filesLoading ? <Skeleton className="h-8 w-12" /> : fileCount}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Ordner</CardTitle>
            <Folder className="h-4 w-4 text-yellow-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {filesLoading ? <Skeleton className="h-8 w-12" /> : folderCount}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Speicher</CardTitle>
            <HardDrive className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {filesLoading ? <Skeleton className="h-8 w-12" /> : formatFileSize(totalSize)}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Zuletzt geaendert</CardTitle>
            <Clock className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {recentLoading ? <Skeleton className="h-8 w-12" /> : recentFiles?.length ?? 0}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Recent Files */}
      <Card>
        <CardHeader>
          <CardTitle>Zuletzt geaenderte Dateien</CardTitle>
          <CardDescription>Die neuesten Änderungen in Nextcloud</CardDescription>
        </CardHeader>
        <CardContent>
          <ScrollArea className="h-[400px]">
            {recentLoading ? (
              <div className="space-y-2">
                {Array.from({ length: 6 }).map((_, i) => (
                  <Skeleton key={i} className="h-16 w-full" />
                ))}
              </div>
            ) : recentFiles && recentFiles.length > 0 ? (
              <div className="space-y-2">
                {recentFiles.map((file, index) => {
                  const Icon = getFileIcon(file);
                  const colorClass = 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.03 }}
                      className="flex items-center gap-4 rounded-lg border p-4 transition-colors hover:bg-muted/50"
                    >
                      <div
                        className={cn(
                          'flex h-12 w-12 items-center justify-center rounded-lg',
                          colorClass
                        )}
                      >
                        <Icon className="h-6 w-6" />
                      </div>

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

                      {file.downloadUrl && (
                        <Button variant="ghost" size="icon" asChild>
                          <a href={file.downloadUrl} download>
                            <Download className="h-4 w-4" />
                          </a>
                        </Button>
                      )}
                    </motion.div>
                  );
                })}
              </div>
            ) : (
              <div className="flex items-center justify-center py-8 text-muted-foreground">
                <Cloud className="mr-2 h-5 w-5" />
                {t('noFiles')}
              </div>
            )}
          </ScrollArea>
        </CardContent>
      </Card>
    </div>
  );
}
