'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  Search,
  MoreHorizontal,
  UserPlus,
  Ban,
  CheckCircle2,
  XCircle,
  Eye,
  Trash2,
  Copy,
  Link,
  Loader2,
} from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { mockUsers, formatNumber, formatCurrency, formatDate, type User } from '@/lib/mock-data';
import {
  apiListUsers,
  apiUpdateUser,
  apiDeleteUser,
  apiCreateInvitation,
  type ApiUser,
} from '@/lib/api';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/toast';

function apiUserToUser(u: ApiUser): User {
  return {
    id: u.id,
    name: u.name,
    email: u.email,
    plan: u.plan as User['plan'],
    status: u.status as User['status'],
    createdAt: u.createdAt,
    lastActive: u.lastActive,
    totalTokensUsed: u.totalTokensUsed,
    totalRequests: u.totalRequests,
    monthlySpend: u.monthlySpend,
  };
}

const statusConfig = {
  active: { label: 'Active', color: 'bg-emerald-50 text-emerald-700', icon: CheckCircle2 },
  inactive: { label: 'Inactive', color: 'bg-amber-50 text-amber-700', icon: XCircle },
  suspended: { label: 'Suspended', color: 'bg-red-50 text-red-700', icon: Ban },
};

const planConfig = {
  free: { label: 'Free', color: '' },
  pro: { label: 'Pro', color: 'bg-blue-50 text-blue-700' },
  enterprise: { label: 'Enterprise', color: 'bg-violet-50 text-violet-700' },
};

export default function UsersPage() {
  const router = useRouter();
  const { toast } = useToast();
  const [users, setUsers] = useState<User[]>(mockUsers);
  const [, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [planFilter, setPlanFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [bulkLoading, setBulkLoading] = useState(false);

  // Invite dialog state
  const [showInvite, setShowInvite] = useState(false);
  const [invitePlan, setInvitePlan] = useState<string>('pro');
  const [inviteDescription, setInviteDescription] = useState('');
  const [inviteCreating, setInviteCreating] = useState(false);
  const [inviteLink, setInviteLink] = useState<string | null>(null);
  const [inviteCopied, setInviteCopied] = useState(false);

  const toggleSelect = (id: string) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const toggleSelectAll = () => {
    if (selectedIds.size === filtered.length) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(filtered.map(u => u.id)));
    }
  };

  const handleInvite = async () => {
    setInviteCreating(true);
    const { data, error } = await apiCreateInvitation({
      description: inviteDescription || 'Invited from Users page',
      grantPlan: invitePlan,
      maxUses: 1,
    });
    setInviteCreating(false);
    if (data) {
      const userDashboardUrl =
        process.env.NEXT_PUBLIC_USER_DASHBOARD_URL || 'http://localhost:3002';
      setInviteLink(`${userDashboardUrl}/login?ref=${encodeURIComponent(data.code)}`);
    } else {
      toast({
        title: 'Failed to create invite',
        description: error || 'Unknown error',
        variant: 'error',
      });
    }
  };

  const copyInviteLink = () => {
    if (!inviteLink) return;
    navigator.clipboard.writeText(inviteLink);
    setInviteCopied(true);
    setTimeout(() => setInviteCopied(false), 2000);
  };

  const handleChangePlan = async (userId: string, newPlan: string) => {
    const { error } = await apiUpdateUser(userId, { plan: newPlan });
    if (!error) {
      setUsers(prev =>
        prev.map(u => (u.id === userId ? { ...u, plan: newPlan as User['plan'] } : u))
      );
      toast({ title: `Plan changed to ${newPlan}`, variant: 'success' });
    } else {
      toast({ title: 'Failed to change plan', description: error, variant: 'error' });
    }
  };

  const handleToggleSuspend = async (user: User) => {
    const newStatus = user.status === 'suspended' ? 'active' : 'suspended';
    const { error } = await apiUpdateUser(user.id, { status: newStatus });
    if (!error) {
      setUsers(prev =>
        prev.map(u => (u.id === user.id ? { ...u, status: newStatus as User['status'] } : u))
      );
      toast({
        title: `User ${newStatus === 'suspended' ? 'suspended' : 'activated'}`,
        variant: newStatus === 'suspended' ? 'warning' : 'success',
      });
    } else {
      toast({ title: 'Action failed', description: error, variant: 'error' });
    }
  };

  const bulkAction = async (action: 'activate' | 'suspend' | 'delete') => {
    if (selectedIds.size === 0) return;
    setBulkLoading(true);
    try {
      for (const userId of selectedIds) {
        if (action === 'delete') {
          await apiDeleteUser(userId);
        } else {
          const status = action === 'activate' ? 'active' : 'suspended';
          await apiUpdateUser(userId, { status });
        }
      }

      // Update local state
      setUsers(prev =>
        action === 'delete'
          ? prev.filter(u => !selectedIds.has(u.id))
          : prev.map(u =>
              selectedIds.has(u.id)
                ? { ...u, status: action === 'activate' ? 'active' : 'suspended' }
                : u
            )
      );
      setSelectedIds(new Set());
      const count = selectedIds.size;
      toast({
        title:
          action === 'delete'
            ? `${count} user${count !== 1 ? 's' : ''} deleted`
            : `${count} user${count !== 1 ? 's' : ''} ${action === 'activate' ? 'activated' : 'suspended'}`,
        variant: action === 'delete' ? 'warning' : 'success',
      });
    } catch (e) {
      console.error('Bulk action failed:', e);
      toast({ title: 'Bulk action failed', description: String(e), variant: 'error' });
    } finally {
      setBulkLoading(false);
    }
  };

  useEffect(() => {
    apiListUsers()
      .then(({ data }) => {
        if (data?.users?.length) {
          setUsers(data.users.map(apiUserToUser));
        }
      })
      .finally(() => setLoading(false));
  }, []);

  const filtered = users.filter(u => {
    const matchesSearch =
      u.name.toLowerCase().includes(search.toLowerCase()) ||
      u.email.toLowerCase().includes(search.toLowerCase());
    const matchesPlan = planFilter === 'all' || u.plan === planFilter;
    const matchesStatus = statusFilter === 'all' || u.status === statusFilter;
    return matchesSearch && matchesPlan && matchesStatus;
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Users</h1>
          <p className="text-muted-foreground">Manage platform users and their subscriptions</p>
        </div>
        <Button
          onClick={() => {
            setShowInvite(true);
            setInviteLink(null);
            setInviteDescription('');
            setInvitePlan('pro');
            setInviteCopied(false);
          }}
        >
          <UserPlus className="mr-2 h-4 w-4" />
          Invite User
        </Button>
      </div>

      {/* Bulk Actions Bar */}
      {selectedIds.size > 0 && (
        <Card className="border-primary/50 bg-primary/5">
          <CardContent className="pt-4 pb-4">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium">
                {selectedIds.size} user{selectedIds.size !== 1 ? 's' : ''} selected
              </span>
              <div className="flex gap-2">
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => bulkAction('activate')}
                  disabled={bulkLoading}
                >
                  <CheckCircle2 className="mr-1 h-3.5 w-3.5 text-emerald-600" />
                  Activate
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => bulkAction('suspend')}
                  disabled={bulkLoading}
                >
                  <Ban className="mr-1 h-3.5 w-3.5 text-amber-600" />
                  Suspend
                </Button>
                <Button
                  size="sm"
                  variant="outline"
                  className="text-red-600 hover:text-red-700"
                  onClick={() => {
                    if (confirm(`Delete ${selectedIds.size} user(s)? This cannot be undone.`)) {
                      bulkAction('delete');
                    }
                  }}
                  disabled={bulkLoading}
                >
                  <Trash2 className="mr-1 h-3.5 w-3.5" />
                  Delete
                </Button>
                <Button size="sm" variant="ghost" onClick={() => setSelectedIds(new Set())}>
                  Clear
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Filters */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex flex-wrap gap-4">
            <div className="relative flex-1 min-w-[200px]">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Search by name or email..."
                value={search}
                onChange={e => setSearch(e.target.value)}
                className="pl-9"
              />
            </div>
            <Select value={planFilter} onValueChange={setPlanFilter}>
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="Plan" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Plans</SelectItem>
                <SelectItem value="free">Free</SelectItem>
                <SelectItem value="pro">Pro</SelectItem>
                <SelectItem value="enterprise">Enterprise</SelectItem>
              </SelectContent>
            </Select>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-[150px]">
                <SelectValue placeholder="Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All Status</SelectItem>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="inactive">Inactive</SelectItem>
                <SelectItem value="suspended">Suspended</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* Users Table */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">
            {filtered.length} user{filtered.length !== 1 ? 's' : ''}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[40px]">
                  <input
                    type="checkbox"
                    className="rounded border-gray-300"
                    checked={filtered.length > 0 && selectedIds.size === filtered.length}
                    onChange={toggleSelectAll}
                  />
                </TableHead>
                <TableHead>User</TableHead>
                <TableHead>Plan</TableHead>
                <TableHead>Status</TableHead>
                <TableHead className="text-right">Tokens Used</TableHead>
                <TableHead className="text-right">Requests</TableHead>
                <TableHead className="text-right">Monthly Spend</TableHead>
                <TableHead>Last Active</TableHead>
                <TableHead className="w-[50px]" />
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map(user => {
                const status = statusConfig[user.status];
                const plan = planConfig[user.plan];
                return (
                  <TableRow
                    key={user.id}
                    className={selectedIds.has(user.id) ? 'bg-primary/5' : ''}
                  >
                    <TableCell>
                      <input
                        type="checkbox"
                        className="rounded border-gray-300"
                        checked={selectedIds.has(user.id)}
                        onChange={() => toggleSelect(user.id)}
                      />
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center gap-3">
                        <div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted text-xs font-bold">
                          {user.name
                            .split(' ')
                            .map(n => n[0])
                            .join('')}
                        </div>
                        <div>
                          <p className="font-medium">{user.name}</p>
                          <p className="text-xs text-muted-foreground">{user.email}</p>
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary" className={plan.color}>
                        {plan.label}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="secondary" className={status.color}>
                        <status.icon className="mr-1 h-3 w-3" />
                        {status.label}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatNumber(user.totalTokensUsed)}
                    </TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatNumber(user.totalRequests)}
                    </TableCell>
                    <TableCell className="text-right font-mono text-sm">
                      {formatCurrency(user.monthlySpend)}
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {formatDate(user.lastActive)}
                    </TableCell>
                    <TableCell>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8">
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem onClick={() => setSelectedUser(user)}>
                            <Eye className="mr-2 h-4 w-4" />
                            Quick View
                          </DropdownMenuItem>
                          <DropdownMenuItem onClick={() => router.push(`/users/${user.id}`)}>
                            <Eye className="mr-2 h-4 w-4" />
                            View as User
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            onClick={() =>
                              handleChangePlan(
                                user.id,
                                user.plan === 'free'
                                  ? 'pro'
                                  : user.plan === 'pro'
                                    ? 'enterprise'
                                    : 'free'
                              )
                            }
                          >
                            Cycle Plan ({user.plan} →{' '}
                            {user.plan === 'free'
                              ? 'pro'
                              : user.plan === 'pro'
                                ? 'enterprise'
                                : 'free'}
                            )
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem
                            className="text-red-600"
                            onClick={() => handleToggleSuspend(user)}
                          >
                            <Ban className="mr-2 h-4 w-4" />
                            {user.status === 'suspended' ? 'Unsuspend' : 'Suspend'}
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                );
              })}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* User Detail Dialog */}
      <Dialog open={!!selectedUser} onOpenChange={() => setSelectedUser(null)}>
        <DialogContent className="max-w-lg">
          <DialogHeader>
            <DialogTitle>{selectedUser?.name}</DialogTitle>
            <DialogDescription>{selectedUser?.email}</DialogDescription>
          </DialogHeader>
          {selectedUser && (
            <div className="space-y-4 pt-2">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">Plan</p>
                  <Badge variant="secondary" className={planConfig[selectedUser.plan].color}>
                    {planConfig[selectedUser.plan].label}
                  </Badge>
                </div>
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">Status</p>
                  <Badge variant="secondary" className={statusConfig[selectedUser.status].color}>
                    {statusConfig[selectedUser.status].label}
                  </Badge>
                </div>
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">Member Since</p>
                  <p className="text-sm font-medium">{formatDate(selectedUser.createdAt)}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">Last Active</p>
                  <p className="text-sm font-medium">{formatDate(selectedUser.lastActive)}</p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">Total Tokens Used</p>
                  <p className="text-sm font-medium font-mono">
                    {formatNumber(selectedUser.totalTokensUsed)}
                  </p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">Total Requests</p>
                  <p className="text-sm font-medium font-mono">
                    {formatNumber(selectedUser.totalRequests)}
                  </p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">Monthly Spend</p>
                  <p className="text-sm font-medium font-mono">
                    {formatCurrency(selectedUser.monthlySpend)}
                  </p>
                </div>
                <div className="space-y-1">
                  <p className="text-xs text-muted-foreground">User ID</p>
                  <p className="text-sm font-mono text-muted-foreground">{selectedUser.id}</p>
                </div>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* Invite User Dialog */}
      <Dialog open={showInvite} onOpenChange={setShowInvite}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Invite User</DialogTitle>
            <DialogDescription>
              Generate a single-use invite link to share with a new user.
            </DialogDescription>
          </DialogHeader>

          {!inviteLink ? (
            <>
              <div className="space-y-4 py-2">
                <div className="space-y-2">
                  <Label>Grant Plan</Label>
                  <Select value={invitePlan} onValueChange={setInvitePlan}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="pro">Pro</SelectItem>
                      <SelectItem value="enterprise">Enterprise</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Description (optional)</Label>
                  <Input
                    placeholder="e.g. Invite for John Doe"
                    value={inviteDescription}
                    onChange={e => setInviteDescription(e.target.value)}
                  />
                </div>
              </div>
              <DialogFooter>
                <Button variant="outline" onClick={() => setShowInvite(false)}>
                  Cancel
                </Button>
                <Button onClick={handleInvite} disabled={inviteCreating}>
                  {inviteCreating ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Creating...
                    </>
                  ) : (
                    <>
                      <Link className="mr-2 h-4 w-4" />
                      Generate Link
                    </>
                  )}
                </Button>
              </DialogFooter>
            </>
          ) : (
            <div className="space-y-4 py-2">
              <div className="rounded-lg border bg-muted/50 p-4">
                <p className="text-xs text-muted-foreground mb-2">
                  Share this link with the user to register:
                </p>
                <div className="flex items-center gap-2">
                  <code className="flex-1 text-sm font-mono break-all select-all">
                    {inviteLink}
                  </code>
                  <Button variant="ghost" size="icon" className="shrink-0" onClick={copyInviteLink}>
                    <Copy className="h-4 w-4" />
                  </Button>
                </div>
                {inviteCopied && (
                  <p className="text-xs text-emerald-600 mt-1">Copied to clipboard!</p>
                )}
              </div>
              <p className="text-xs text-muted-foreground">
                This is a single-use invite that grants <strong>{invitePlan}</strong> plan access.
              </p>
              <DialogFooter>
                <Button variant="outline" onClick={() => setShowInvite(false)}>
                  Done
                </Button>
                <Button onClick={copyInviteLink}>
                  <Copy className="mr-2 h-4 w-4" />
                  {inviteCopied ? 'Copied!' : 'Copy Link'}
                </Button>
              </DialogFooter>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
