'use client';

import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { motion } from 'framer-motion';
import { ColumnDef } from '@tanstack/react-table';
import {
  MoreHorizontal,
  UserPlus,
  Mail,
  Shield,
  Edit,
  Trash2,
  UserCheck,
  UserX,
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Checkbox } from '@/components/ui/checkbox';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { DataTable, DataTableColumnHeader } from '@/components/ui/data-table';
import type { User, UserRole } from '@/types';

interface UsersContentProps {
  locale: string;
}

// Mock user data
const mockUsers: (User & { lastActive: string })[] = [
  {
    id: '1',
    email: 'admin@example.com',
    firstName: 'Admin',
    lastName: 'User',
    displayName: 'Admin User',
    roles: ['admin'],
    isActive: true,
    createdAt: new Date('2023-01-15'),
    updatedAt: new Date('2024-01-20'),
    lastActive: 'vor 5 Minuten',
  },
  {
    id: '2',
    email: 'max.mustermann@example.com',
    firstName: 'Max',
    lastName: 'Mustermann',
    displayName: 'Max Mustermann',
    roles: ['employee'],
    departmentId: '1',
    isActive: true,
    createdAt: new Date('2023-06-01'),
    updatedAt: new Date('2024-01-18'),
    lastActive: 'vor 2 Stunden',
  },
  {
    id: '3',
    email: 'anna.schmidt@example.com',
    firstName: 'Anna',
    lastName: 'Schmidt',
    displayName: 'Anna Schmidt',
    roles: ['department_head', 'employee'],
    departmentId: '2',
    isActive: true,
    createdAt: new Date('2023-03-10'),
    updatedAt: new Date('2024-01-19'),
    lastActive: 'vor 1 Tag',
  },
  {
    id: '4',
    email: 'peter.mueller@example.com',
    firstName: 'Peter',
    lastName: 'Mueller',
    displayName: 'Peter Mueller',
    roles: ['manager', 'employee'],
    departmentId: '1',
    isActive: true,
    createdAt: new Date('2022-11-05'),
    updatedAt: new Date('2024-01-15'),
    lastActive: 'vor 3 Tagen',
  },
  {
    id: '5',
    email: 'inactive.user@example.com',
    firstName: 'Inactive',
    lastName: 'User',
    displayName: 'Inactive User',
    roles: ['employee'],
    isActive: false,
    createdAt: new Date('2023-02-20'),
    updatedAt: new Date('2023-12-01'),
    lastActive: 'vor 30 Tagen',
  },
];

type UserWithLastActive = User & { lastActive: string };

const roleColors: Record<UserRole, 'default' | 'secondary' | 'destructive' | 'outline'> = {
  admin: 'destructive',
  manager: 'default',
  department_head: 'secondary',
  employee: 'outline',
};

/**
 * Users management content with DataTable
 */
export function UsersContent({ locale }: UsersContentProps) {
  const t = useTranslations('admin');
  const [users] = useState<UserWithLastActive[]>(mockUsers);

  const columns: ColumnDef<UserWithLastActive>[] = [
    {
      id: 'select',
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && 'indeterminate')
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="Alle auswaehlen"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="Zeile auswaehlen"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    },
    {
      accessorKey: 'displayName',
      header: ({ column }) => <DataTableColumnHeader column={column} title="Name" />,
      cell: ({ row }) => {
        const user = row.original;
        const initials = `${user.firstName[0]}${user.lastName[0]}`.toUpperCase();

        return (
          <div className="flex items-center gap-3">
            <Avatar className="h-8 w-8">
              <AvatarImage src={user.avatarUrl} />
              <AvatarFallback className="text-xs">{initials}</AvatarFallback>
            </Avatar>
            <div>
              <p className="font-medium">{user.displayName}</p>
              <p className="text-xs text-muted-foreground">{user.email}</p>
            </div>
          </div>
        );
      },
    },
    {
      accessorKey: 'roles',
      header: ({ column }) => <DataTableColumnHeader column={column} title="Rollen" />,
      cell: ({ row }) => {
        const roles = row.original.roles;
        return (
          <div className="flex flex-wrap gap-1">
            {roles.map((role) => (
              <Badge key={role} variant={roleColors[role]} className="text-xs">
                {role}
              </Badge>
            ))}
          </div>
        );
      },
      filterFn: (row, id, value) => {
        return row.original.roles.some((role) => value.includes(role));
      },
    },
    {
      accessorKey: 'isActive',
      header: ({ column }) => <DataTableColumnHeader column={column} title="Status" />,
      cell: ({ row }) => {
        const isActive = row.original.isActive;
        return (
          <Badge variant={isActive ? 'success' : 'secondary'}>
            {isActive ? 'Aktiv' : 'Inaktiv'}
          </Badge>
        );
      },
    },
    {
      accessorKey: 'lastActive',
      header: ({ column }) => <DataTableColumnHeader column={column} title="Letzte Aktivitaet" />,
      cell: ({ row }) => (
        <span className="text-sm text-muted-foreground">{row.original.lastActive}</span>
      ),
    },
    {
      id: 'actions',
      enableHiding: false,
      cell: ({ row }) => {
        const user = row.original;

        return (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon" className="h-8 w-8">
                <MoreHorizontal className="h-4 w-4" />
                <span className="sr-only">Aktionen oeffnen</span>
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Aktionen</DropdownMenuLabel>
              <DropdownMenuItem>
                <Edit className="mr-2 h-4 w-4" />
                Bearbeiten
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Mail className="mr-2 h-4 w-4" />
                E-Mail senden
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Shield className="mr-2 h-4 w-4" />
                Rollen verwalten
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              {user.isActive ? (
                <DropdownMenuItem className="text-yellow-600">
                  <UserX className="mr-2 h-4 w-4" />
                  Deaktivieren
                </DropdownMenuItem>
              ) : (
                <DropdownMenuItem className="text-green-600">
                  <UserCheck className="mr-2 h-4 w-4" />
                  Aktivieren
                </DropdownMenuItem>
              )}
              <DropdownMenuItem className="text-destructive">
                <Trash2 className="mr-2 h-4 w-4" />
                Loeschen
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        );
      },
    },
  ];

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
      className="space-y-4"
    >
      {/* Actions Bar */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold">Benutzerverwaltung</h2>
          <p className="text-sm text-muted-foreground">
            {users.length} Benutzer im System
          </p>
        </div>

        <Button className="gap-2">
          <UserPlus className="h-4 w-4" />
          Benutzer hinzufuegen
        </Button>
      </div>

      {/* Data Table */}
      <DataTable
        columns={columns}
        data={users}
        searchColumn="displayName"
        searchPlaceholder="Benutzer suchen..."
      />
    </motion.div>
  );
}
