'use client';

import React from 'react';
import { Card } from '@/ui/Card';
import { Table, TableHead, TableBody, TableRow, TableHeader, TableCell } from '@/ui/Table';
import { Button } from '@/ui/Button';
import { Text } from '@/ui/Text';
import { Heading } from '@/ui/Heading';
import { Box } from '@/ui/Box';
import { Stack } from '@/ui/Stack';
import { Container } from '@/ui/Container';
import { Icon } from '@/ui/Icon';
import { StatusBadge } from '@/ui/StatusBadge';
import { InfoBox } from '@/ui/InfoBox';
import {
  RefreshCw,
  Shield,
  Trash2,
  Users
} from 'lucide-react';
import { AdminUsersViewData } from '@/lib/view-data/AdminUsersViewData';
import { UserFilters } from '@/components/admin/UserFilters';
import { UserStatsSummary } from '@/components/admin/UserStatsSummary';
import { Surface } from '@/ui/Surface';

interface AdminUsersTemplateProps {
  viewData: AdminUsersViewData;
  onRefresh: () => void;
  onSearch: (search: string) => void;
  onFilterRole: (role: string) => void;
  onFilterStatus: (status: string) => void;
  onClearFilters: () => void;
  onUpdateStatus: (userId: string, status: string) => void;
  onDeleteUser: (userId: string) => void;
  search: string;
  roleFilter: string;
  statusFilter: string;
  loading: boolean;
  error: string | null;
  deletingUser: string | null;
}

export function AdminUsersTemplate({
  viewData,
  onRefresh,
  onSearch,
  onFilterRole,
  onFilterStatus,
  onClearFilters,
  onUpdateStatus,
  onDeleteUser,
  search,
  roleFilter,
  statusFilter,
  loading,
  error,
  deletingUser
}: AdminUsersTemplateProps) {
  const getStatusBadgeVariant = (status: string): 'success' | 'warning' | 'error' | 'info' => {
    switch (status) {
      case 'active': return 'success';
      case 'suspended': return 'warning';
      case 'deleted': return 'error';
      default: return 'info';
    }
  };

  const getRoleBadgeStyle = (role: string) => {
    switch (role) {
      case 'owner': return { backgroundColor: 'rgba(168, 85, 247, 0.2)', color: '#d8b4fe', border: '1px solid rgba(168, 85, 247, 0.3)' };
      case 'admin': return { backgroundColor: 'rgba(59, 130, 246, 0.2)', color: '#93c5fd', border: '1px solid rgba(59, 130, 246, 0.3)' };
      default: return { backgroundColor: 'rgba(115, 115, 115, 0.2)', color: '#d1d5db', border: '1px solid rgba(115, 115, 115, 0.3)' };
    }
  };

  return (
    <Container size="lg" py={6}>
      <Stack gap={6}>
        {/* Header */}
        <Stack direction="row" align="center" justify="between">
          <Box>
            <Heading level={1}>User Management</Heading>
            <Text size="sm" color="text-gray-400" block mt={1}>Manage and monitor all system users</Text>
          </Box>
          <Button
            onClick={onRefresh}
            disabled={loading}
            variant="secondary"
            icon={<Icon icon={RefreshCw} size={4} className={loading ? 'animate-spin' : ''} />}
          >
            Refresh
          </Button>
        </Stack>

        {/* Error Banner */}
        {error && (
          <InfoBox 
            icon={Users}
            title="Error"
            description={error}
            variant="warning"
          />
        )}

        {/* Filters Card */}
        <UserFilters 
          search={search}
          roleFilter={roleFilter}
          statusFilter={statusFilter}
          onSearch={onSearch}
          onFilterRole={onFilterRole}
          onFilterStatus={onFilterStatus}
          onClearFilters={onClearFilters}
        />

        {/* Users Table */}
        <Card p={0}>
          {loading ? (
            <Stack center py={12} gap={3}>
              <Box className="animate-spin" style={{ borderRadius: '9999px', height: '2rem', width: '2rem', borderBottom: '2px solid #3b82f6' }} />
              <Text color="text-gray-400">Loading users...</Text>
            </Stack>
          ) : !viewData.users || viewData.users.length === 0 ? (
            <Stack center py={12} gap={3}>
              <Icon icon={Users} size={12} color="#525252" />
              <Text color="text-gray-400">No users found</Text>
              <Button
                onClick={onClearFilters}
                variant="ghost"
                size="sm"
              >
                Clear filters
              </Button>
            </Stack>
          ) : (
            <Table>
              <TableHead>
                <TableRow>
                  <TableHeader>User</TableHeader>
                  <TableHeader>Email</TableHeader>
                  <TableHeader>Roles</TableHeader>
                  <TableHeader>Status</TableHeader>
                  <TableHeader>Last Login</TableHeader>
                  <TableHeader>Actions</TableHeader>
                </TableRow>
              </TableHead>
              <TableBody>
                {viewData.users.map((user) => (
                  <TableRow key={user.id}>
                    <TableCell>
                      <Stack direction="row" align="center" gap={3}>
                        <Surface variant="muted" rounded="full" padding={2} style={{ backgroundColor: 'rgba(59, 130, 246, 0.2)' }}>
                          <Icon icon={Shield} size={4} color="#3b82f6" />
                        </Surface>
                        <Box>
                          <Text weight="medium" color="text-white" block>{user.displayName}</Text>
                          <Text size="xs" color="text-gray-500" block>ID: {user.id}</Text>
                          {user.primaryDriverId && (
                            <Text size="xs" color="text-gray-500" block>Driver: {user.primaryDriverId}</Text>
                          )}
                        </Box>
                      </Stack>
                    </TableCell>
                    <TableCell>
                      <Text size="sm" color="text-gray-300">{user.email}</Text>
                    </TableCell>
                    <TableCell>
                      <Stack direction="row" gap={1} wrap>
                        {user.roles.map((role, idx) => {
                          const style = getRoleBadgeStyle(role);
                          return (
                            <Surface 
                              key={idx} 
                              variant="muted" 
                              rounded="full" 
                              padding={1} 
                              style={{ 
                                paddingLeft: '0.5rem', 
                                paddingRight: '0.5rem',
                                backgroundColor: style.backgroundColor,
                                color: style.color,
                                borderColor: style.border,
                                border: '1px solid'
                              }}
                            >
                              <Text size="xs" weight="medium">{role.charAt(0).toUpperCase() + role.slice(1)}</Text>
                            </Surface>
                          );
                        })}
                      </Stack>
                    </TableCell>
                    <TableCell>
                      <StatusBadge variant={getStatusBadgeVariant(user.status)}>
                        {user.status.charAt(0).toUpperCase() + user.status.slice(1)}
                      </StatusBadge>
                    </TableCell>
                    <TableCell>
                      <Text size="sm" color="text-gray-400">
                        {user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleDateString() : 'Never'}
                      </Text>
                    </TableCell>
                    <TableCell>
                      <Stack direction="row" align="center" gap={2}>
                        {user.status === 'active' && (
                          <Button
                            onClick={() => onUpdateStatus(user.id, 'suspended')}
                            variant="secondary"
                            size="sm"
                          >
                            Suspend
                          </Button>
                        )}
                        {user.status === 'suspended' && (
                          <Button
                            onClick={() => onUpdateStatus(user.id, 'active')}
                            variant="secondary"
                            size="sm"
                          >
                            Activate
                          </Button>
                        )}
                        {user.status !== 'deleted' && (
                          <Button
                            onClick={() => onDeleteUser(user.id)}
                            disabled={deletingUser === user.id}
                            variant="secondary"
                            size="sm"
                            icon={<Icon icon={Trash2} size={3} />}
                          >
                            {deletingUser === user.id ? 'Deleting...' : 'Delete'}
                          </Button>
                        )}
                      </Stack>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </Card>

        {/* Stats Summary */}
        {viewData.users.length > 0 && (
          <UserStatsSummary 
            total={viewData.total}
            activeCount={viewData.activeUserCount}
            adminCount={viewData.adminCount}
          />
        )}
      </Stack>
    </Container>
  );
}
