'use client';

import { useState, useEffect, useCallback } from 'react';
import { Search, Plus, Trash2, CheckCircle, Ban, Shield, Crown, UserPlus } from 'lucide-react';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';

const ORANGE_BTN = 'bg-gradient-to-r from-orange-600 to-amber-500 shadow-sm';
const roleLabels: Record<string, string> = { general: 'General User', houseOwner: 'House Owner', shopOwner: 'Shop Owner', seller: 'Seller', admin: 'Admin' };

export function AdminUsers() {
  const [users, setUsers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [showAddDialog, setShowAddDialog] = useState(false);
  const [roleChangeUser, setRoleChangeUser] = useState<any>(null);
  const [newRole, setNewRole] = useState('');
  const [addName, setAddName] = useState('');
  const [addEmail, setAddEmail] = useState('');
  const [addPhone, setAddPhone] = useState('');
  const [addPassword, setAddPassword] = useState('');
  const [addRole, setAddRole] = useState('general');
  const [addLoading, setAddLoading] = useState(false);

  const fetchUsers = useCallback(async () => {
    try { const r = await fetch('/api/admin/users'); const d = await r.json(); if (d.success) setUsers(d.users); } catch { }
    finally { setLoading(false); }
  }, []);
  useEffect(() => { fetchUsers(); }, [fetchUsers]);

  const toggleActive = async (userId: string, cur: boolean) => {
    try { const r = await fetch('/api/admin/users', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId, isActive: !cur }) }); const d = await r.json(); if (d.success) fetchUsers(); } catch { }
  };
  const deleteUser = async (userId: string) => {
    try { const r = await fetch('/api/admin/users', { method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId }) }); const d = await r.json(); if (d.success) fetchUsers(); } catch { }
  };
  const changeRole = async (userId: string, roles: string) => {
    try { const r = await fetch('/api/admin/users', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId, roles }) }); const d = await r.json(); if (d.success) { setRoleChangeUser(null); fetchUsers(); } } catch { }
  };
  const addUser = async (e: React.FormEvent) => {
    e.preventDefault(); setAddLoading(true);
    try {
      const r = await fetch('/api/admin/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: addName, email: addEmail, phone: addPhone, password: addPassword, roles: addRole }) });
      const d = await r.json();
      if (d.success) { setShowAddDialog(false); setAddName(''); setAddEmail(''); setAddPhone(''); setAddPassword(''); setAddRole('general'); fetchUsers(); }
    } catch { } finally { setAddLoading(false); }
  };

  const filtered = users.filter((u) => u.name?.toLowerCase().includes(searchQuery.toLowerCase()) || u.email?.toLowerCase().includes(searchQuery.toLowerCase()));
  if (loading) return <div className="flex items-center justify-center py-20"><span className="h-8 w-8 animate-spin rounded-full border-4 border-orange-500 border-t-transparent" /></div>;

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input placeholder="Search users..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-9" />
        </div>
        <Button className={`gap-2 ${ORANGE_BTN}`} onClick={() => setShowAddDialog(true)}><Plus className="h-4 w-4" />Add User</Button>
      </div>
      <Card className="border-0 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="bg-slate-50/80 dark:bg-slate-800/50">
                <TableHead>User</TableHead><TableHead className="hidden sm:table-cell">Email</TableHead><TableHead>Role</TableHead><TableHead className="hidden md:table-cell">Status</TableHead><TableHead className="hidden lg:table-cell">Joined</TableHead><TableHead>Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((u) => (
                <TableRow key={u.id} className="hover:bg-slate-50/50 dark:hover:bg-slate-800/30">
                  <TableCell>
                    <div className="flex items-center gap-3">
                      <div className="flex h-9 w-9 items-center justify-center rounded-full bg-gradient-to-br from-orange-400 to-amber-400 text-xs font-bold text-white shadow-sm">{u.name?.charAt(0).toUpperCase() || '?'}</div>
                      <div><p className="text-sm font-medium">{u.name}</p><p className="text-xs text-muted-foreground sm:hidden">{u.email}</p></div>
                    </div>
                  </TableCell>
                  <TableCell className="hidden text-sm sm:table-cell">{u.email}</TableCell>
                  <TableCell><Badge variant="outline" className="text-[10px] font-medium">{roleLabels[u.roles] || u.roles || 'General'}</Badge></TableCell>
                  <TableCell className="hidden md:table-cell"><Badge className={`text-[10px] border-0 ${u.isActive ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-950/30 dark:text-emerald-400' : 'bg-red-50 text-red-700 dark:bg-red-950/30 dark:text-red-400'}`}>{u.isActive ? 'Active' : 'Suspended'}</Badge></TableCell>
                  <TableCell className="hidden text-xs text-muted-foreground lg:table-cell">{new Date(u.createdAt).toLocaleDateString()}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1">
                      <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => toggleActive(u.id, u.isActive)} title={u.isActive ? 'Suspend' : 'Activate'}>
                        {u.isActive ? <Ban className="h-3.5 w-3.5 text-amber-500" /> : <CheckCircle className="h-3.5 w-3.5 text-emerald-500" />}
                      </Button>
                      <Button variant="ghost" size="icon" className="h-8 w-8" onClick={() => { setRoleChangeUser(u); setNewRole(u.roles || 'general'); }}><Shield className="h-3.5 w-3.5 text-orange-500" /></Button>
                      <AlertDialog>
                        <AlertDialogTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8"><Trash2 className="h-3.5 w-3.5 text-destructive" /></Button></AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader><AlertDialogTitle>Delete User</AlertDialogTitle><AlertDialogDescription>Delete {u.name}&apos;s account permanently?</AlertDialogDescription></AlertDialogHeader>
                          <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={() => deleteUser(u.id)} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">Delete</AlertDialogAction></AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
              {filtered.length === 0 && <TableRow><TableCell colSpan={6} className="py-12 text-center text-sm text-muted-foreground">No users found</TableCell></TableRow>}
            </TableBody>
          </Table>
        </div>
      </Card>

      <Dialog open={showAddDialog} onOpenChange={setShowAddDialog}>
        <DialogContent className="sm:max-w-[420px]">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><UserPlus className="h-5 w-5 text-orange-500" />Add New User</DialogTitle><DialogDescription>Create a new user account</DialogDescription></DialogHeader>
          <form onSubmit={addUser} className="space-y-3 pt-2">
            <div className="space-y-1.5"><Label className="text-xs font-medium">Name</Label><Input value={addName} onChange={(e) => setAddName(e.target.value)} required /></div>
            <div className="space-y-1.5"><Label className="text-xs font-medium">Email</Label><Input type="email" value={addEmail} onChange={(e) => setAddEmail(e.target.value)} required /></div>
            <div className="space-y-1.5"><Label className="text-xs font-medium">Phone</Label><Input type="tel" value={addPhone} onChange={(e) => setAddPhone(e.target.value)} /></div>
            <div className="space-y-1.5"><Label className="text-xs font-medium">Password</Label><Input type="password" value={addPassword} onChange={(e) => setAddPassword(e.target.value)} required /></div>
            <div className="space-y-1.5">
              <Label className="text-xs font-medium">Role</Label>
              <select value={addRole} onChange={(e) => setAddRole(e.target.value)} className="w-full rounded-lg border bg-background px-3 py-2 text-sm">
                <option value="general">General User</option><option value="houseOwner">House Owner</option><option value="shopOwner">Shop Owner</option><option value="seller">Seller</option><option value="admin">Admin</option>
              </select>
            </div>
            <Button type="submit" className={`w-full ${ORANGE_BTN} font-semibold`} disabled={addLoading}>{addLoading ? 'Creating...' : 'Create User'}</Button>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog open={!!roleChangeUser} onOpenChange={(o) => { if (!o) setRoleChangeUser(null); }}>
        <DialogContent className="sm:max-w-[380px]">
          <DialogHeader><DialogTitle className="flex items-center gap-2"><Crown className="h-5 w-5 text-orange-500" />Change Role</DialogTitle><DialogDescription>{roleChangeUser && `${roleChangeUser.name} (${roleChangeUser.email})`}</DialogDescription></DialogHeader>
          <div className="space-y-2 py-2">
            {['general', 'houseOwner', 'shopOwner', 'seller', 'admin'].map((r) => (
              <button key={r} type="button" onClick={() => setNewRole(r)} className={`flex w-full items-center gap-3 rounded-xl border px-4 py-3 text-sm transition-all ${newRole === r ? 'border-orange-500 bg-orange-50 font-semibold text-orange-600 dark:bg-orange-950/20 dark:text-orange-400' : 'hover:border-orange-500/30 hover:bg-orange-50/50 dark:hover:bg-orange-950/10'}`}>{roleLabels[r]}</button>
            ))}
            <Button className={`w-full ${ORANGE_BTN} font-semibold mt-2`} onClick={() => roleChangeUser && changeRole(roleChangeUser.id, newRole)}>Update Role</Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
