"use client";

import React, { useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Search, Filter, MoreHorizontal, Shield, UserCheck, UserX } from "lucide-react";
import { getInitials, formatDate } from "@/lib/utils";
import { useApiData } from "@/hooks/use-api-data";

interface AdminUser {
  id: string;
  name: string;
  email: string;
  role: string;
  company: string | null;
  phone: string | null;
  created_at: string;
  updated_at: string;
  subscription_status: string | null;
}

// Fallback mock users
const fallbackUsers: AdminUser[] = [
  { id: "1", name: "John Doe", email: "john@brokerage.com", role: "agent", company: "Doe Brokerage", phone: null, created_at: "2024-06-15", updated_at: "2024-06-15", subscription_status: "active" },
  { id: "2", name: "Admin User", email: "admin@credispo.com", role: "admin", company: "CREdispo", phone: null, created_at: "2024-01-01", updated_at: "2024-01-01", subscription_status: null },
  { id: "3", name: "Robert Thompson", email: "robert@thompsonfamily.com", role: "buyer", company: "Thompson Family Office", phone: null, created_at: "2024-07-10", updated_at: "2024-07-10", subscription_status: null },
];

export default function AdminUsersPage() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterRole, setFilterRole] = useState("all");

  const { data: apiUsers } = useApiData<AdminUser[]>('/api/admin/users', []);
  const allUsers = apiUsers.length > 0 ? apiUsers : fallbackUsers;

  const filteredUsers = allUsers.filter((user) => {
    const matchesSearch =
      user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      user.email.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesRole = filterRole === "all" || user.role === filterRole;
    return matchesSearch && matchesRole;
  });

  const roleColor = (role: string) => {
    switch (role) {
      case "admin":
        return "bg-red-100 text-red-800";
      case "agent":
        return "bg-blue-100 text-blue-800";
      case "buyer":
        return "bg-emerald-100 text-emerald-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  return (
    <div className="space-y-6 animate-page-in">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-navy-900">User Management</h1>
          <p className="text-sm text-navy-500 mt-1">
            {allUsers.length} total users •{" "}
            {allUsers.filter((u) => u.role === "agent").length} agents •{" "}
            {allUsers.filter((u) => u.role === "buyer").length} buyers
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-navy-400" />
          <Input
            placeholder="Search by name or email..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>
        <Select value={filterRole} onValueChange={setFilterRole}>
          <SelectTrigger className="w-full sm:w-40">
            <Filter className="h-4 w-4 mr-2" />
            <SelectValue placeholder="Role" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Roles</SelectItem>
            <SelectItem value="admin">Admin</SelectItem>
            <SelectItem value="agent">Agent</SelectItem>
            <SelectItem value="buyer">Buyer</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Users Table */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto -mx-px">
            <table className="w-full min-w-[750px] zebra-stripe">
              <thead>
                <tr className="border-b border-navy-100 bg-navy-25">
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    User
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Role
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Company
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Subscription
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Status
                  </th>
                  <th className="text-left text-xs font-medium text-navy-500 uppercase tracking-wider px-6 py-3">
                    Joined
                  </th>
                  <th className="px-6 py-3" />
                </tr>
              </thead>
              <tbody className="divide-y divide-navy-50">
                {filteredUsers.map((user) => (
                  <tr key={user.id} className="hover:bg-gold-50/30 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-3">
                        <Avatar className="h-8 w-8">
                          <AvatarFallback className="text-xs">
                            {getInitials(user.name)}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <p className="text-sm font-medium text-navy-900">{user.name}</p>
                          <p className="text-xs text-navy-500">{user.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <Badge className={roleColor(user.role)} variant="secondary">
                        {user.role === "admin" && <Shield className="mr-1 h-3 w-3" />}
                        {user.role}
                      </Badge>
                    </td>
                    <td className="px-6 py-4">
                      <span className="text-sm text-navy-700">{user.company || "—"}</span>
                    </td>
                    <td className="px-6 py-4">
                      {user.subscription_status ? (
                        <Badge
                          variant={user.subscription_status === "active" ? "success" : "warning"}
                        >
                          {user.subscription_status}
                        </Badge>
                      ) : (
                        <span className="text-xs text-navy-400">N/A</span>
                      )}
                    </td>
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-1.5">
                        <UserCheck className="h-3.5 w-3.5 text-emerald-500" />
                        <span className="text-xs text-navy-600 capitalize">active</span>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className="text-xs text-navy-500">{formatDate(user.created_at)}</span>
                    </td>
                    <td className="px-6 py-4">
                      <Button variant="ghost" size="icon" className="h-8 w-8">
                        <MoreHorizontal className="h-4 w-4 text-navy-400" />
                      </Button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
