"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { AdminLayout } from "@/components/admin/admin-layout"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Users,
  UserPlus,
  Search,
  Download,
  Edit,
  Trash2,
  Mail,
  Phone,
  Calendar,
  TrendingUp,
  Eye,
  MoreHorizontal,
} from "lucide-react"

interface User {
  id: string
  name: string
  email: string
  phone: string
  role: "customer" | "admin" | "agent"
  status: "active" | "inactive" | "pending"
  joinDate: string
  lastActive: string
  quotesCount: number
  totalSpent: number
}

interface Customer {
  id: string
  name: string
  email: string
  phone: string
  company?: string
  insuranceType: string
  quoteStatus: "pending" | "approved" | "rejected" | "expired"
  quoteAmount: number
  lastContact: string
  notes: string
}

export default function UserManagement() {
  const router = useRouter()
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")
  const [filterRole, setFilterRole] = useState("all")
  const [filterStatus, setFilterStatus] = useState("all")
  const [selectedUser, setSelectedUser] = useState<User | null>(null)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)

  const [users, setUsers] = useState<User[]>([
    {
      id: "1",
      name: "John Doe",
      email: "john@example.com",
      phone: "+234-801-234-5678",
      role: "customer",
      status: "active",
      joinDate: "2024-01-15",
      lastActive: "2024-01-20",
      quotesCount: 3,
      totalSpent: 150000,
    },
    {
      id: "2",
      name: "Jane Smith",
      email: "jane@company.com",
      phone: "+234-802-345-6789",
      role: "customer",
      status: "active",
      joinDate: "2024-01-10",
      lastActive: "2024-01-19",
      quotesCount: 1,
      totalSpent: 75000,
    },
    {
      id: "3",
      name: "Mike Johnson",
      email: "mike@business.com",
      phone: "+234-803-456-7890",
      role: "customer",
      status: "pending",
      joinDate: "2024-01-18",
      lastActive: "2024-01-18",
      quotesCount: 0,
      totalSpent: 0,
    },
  ])

  const [customers, setCustomers] = useState<Customer[]>([
    {
      id: "1",
      name: "John Doe",
      email: "john@example.com",
      phone: "+234-801-234-5678",
      company: "Tech Solutions Ltd",
      insuranceType: "Business Insurance",
      quoteStatus: "approved",
      quoteAmount: 150000,
      lastContact: "2024-01-20",
      notes: "Interested in comprehensive business coverage",
    },
    {
      id: "2",
      name: "Jane Smith",
      email: "jane@company.com",
      phone: "+234-802-345-6789",
      company: "Marketing Agency",
      insuranceType: "Professional Indemnity",
      quoteStatus: "pending",
      quoteAmount: 75000,
      lastContact: "2024-01-19",
      notes: "Requires quick turnaround for policy activation",
    },
  ])

  useEffect(() => {
    const isLoggedIn = localStorage.getItem("adminLoggedIn")
    if (isLoggedIn !== "true") {
      router.push("/admin")
      return
    }
    setLoading(false)
  }, [router])

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

  const handleDeleteUser = (userId: string) => {
    if (confirm("Are you sure you want to delete this user?")) {
      setUsers(users.filter((user) => user.id !== userId))
    }
  }

  const handleExportUsers = () => {
    const csvContent =
      "data:text/csv;charset=utf-8," +
      "Name,Email,Phone,Role,Status,Join Date,Last Active,Quotes,Total Spent\n" +
      users
        .map(
          (user) =>
            `${user.name},${user.email},${user.phone},${user.role},${user.status},${user.joinDate},${user.lastActive},${user.quotesCount},${user.totalSpent}`,
        )
        .join("\n")

    const encodedUri = encodeURI(csvContent)
    const link = document.createElement("a")
    link.setAttribute("href", encodedUri)
    link.setAttribute("download", "users-export.csv")
    link.click()
  }

  if (loading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center h-64">
          <div className="text-white text-xl">Loading users...</div>
        </div>
      </AdminLayout>
    )
  }

  return (
    <AdminLayout>
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-white">User & Customer Management</h1>
            <p className="text-gray-300">Manage users, customers, and their data</p>
          </div>

          <div className="flex items-center space-x-2">
            <Button
              variant="outline"
              onClick={handleExportUsers}
              className="border-blue-500/30 text-blue-400 hover:bg-blue-500/10 bg-transparent"
            >
              <Download className="w-4 h-4 mr-2" />
              Export
            </Button>

            <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
              <DialogTrigger asChild>
                <Button className="bg-gradient-to-r from-purple-500 to-blue-500 hover:from-purple-600 hover:to-blue-600">
                  <UserPlus className="w-4 h-4 mr-2" />
                  Add User
                </Button>
              </DialogTrigger>
              <DialogContent className="bg-slate-900 border-white/20">
                <DialogHeader>
                  <DialogTitle className="text-white">Add New User</DialogTitle>
                  <DialogDescription className="text-gray-300">Create a new user account</DialogDescription>
                </DialogHeader>
                {/* Add user form would go here */}
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label className="text-white">Name</Label>
                    <Input className="bg-white/10 border-white/20 text-white" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-white">Email</Label>
                    <Input type="email" className="bg-white/10 border-white/20 text-white" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-white">Phone</Label>
                    <Input className="bg-white/10 border-white/20 text-white" />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-white">Role</Label>
                    <Select>
                      <SelectTrigger className="bg-white/10 border-white/20 text-white">
                        <SelectValue placeholder="Select role" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="customer">Customer</SelectItem>
                        <SelectItem value="agent">Agent</SelectItem>
                        <SelectItem value="admin">Admin</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <Button className="w-full bg-gradient-to-r from-purple-500 to-blue-500">Create User</Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
          <Card className="bg-white/10 backdrop-blur-lg border-white/20">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-300 text-sm">Total Users</p>
                  <p className="text-2xl font-bold text-white">{users.length}</p>
                </div>
                <Users className="w-8 h-8 text-purple-400" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-white/10 backdrop-blur-lg border-white/20">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-300 text-sm">Active Users</p>
                  <p className="text-2xl font-bold text-white">{users.filter((u) => u.status === "active").length}</p>
                </div>
                <TrendingUp className="w-8 h-8 text-green-400" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-white/10 backdrop-blur-lg border-white/20">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-300 text-sm">Total Quotes</p>
                  <p className="text-2xl font-bold text-white">{users.reduce((sum, u) => sum + u.quotesCount, 0)}</p>
                </div>
                <Calendar className="w-8 h-8 text-blue-400" />
              </div>
            </CardContent>
          </Card>

          <Card className="bg-white/10 backdrop-blur-lg border-white/20">
            <CardContent className="p-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-gray-300 text-sm">Revenue</p>
                  <p className="text-2xl font-bold text-white">
                    ₦{users.reduce((sum, u) => sum + u.totalSpent, 0).toLocaleString()}
                  </p>
                </div>
                <TrendingUp className="w-8 h-8 text-orange-400" />
              </div>
            </CardContent>
          </Card>
        </div>

        <Tabs defaultValue="users" className="space-y-6">
          <TabsList className="bg-white/10 border-white/20">
            <TabsTrigger value="users" className="data-[state=active]:bg-purple-500/20">
              <Users className="w-4 h-4 mr-2" />
              Users
            </TabsTrigger>
            <TabsTrigger value="customers" className="data-[state=active]:bg-purple-500/20">
              <UserPlus className="w-4 h-4 mr-2" />
              Customers
            </TabsTrigger>
          </TabsList>

          <TabsContent value="users" className="space-y-6">
            <Card className="bg-white/10 backdrop-blur-lg border-white/20">
              <CardContent className="p-6">
                <div className="flex flex-col md:flex-row gap-4">
                  <div className="flex-1">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                      <Input
                        placeholder="Search users..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-10 bg-white/10 border-white/20 text-white"
                      />
                    </div>
                  </div>

                  <Select value={filterRole} onValueChange={setFilterRole}>
                    <SelectTrigger className="w-full md:w-48 bg-white/10 border-white/20 text-white">
                      <SelectValue placeholder="Filter by role" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Roles</SelectItem>
                      <SelectItem value="customer">Customer</SelectItem>
                      <SelectItem value="agent">Agent</SelectItem>
                      <SelectItem value="admin">Admin</SelectItem>
                    </SelectContent>
                  </Select>

                  <Select value={filterStatus} onValueChange={setFilterStatus}>
                    <SelectTrigger className="w-full md:w-48 bg-white/10 border-white/20 text-white">
                      <SelectValue placeholder="Filter by status" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">All Status</SelectItem>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="inactive">Inactive</SelectItem>
                      <SelectItem value="pending">Pending</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardContent>
            </Card>

            <Card className="bg-white/10 backdrop-blur-lg border-white/20">
              <CardHeader>
                <CardTitle className="text-white">Users ({filteredUsers.length})</CardTitle>
                <CardDescription className="text-gray-300">Manage user accounts and permissions</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-white/20">
                        <th className="text-left py-3 px-4 text-white font-semibold">User</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Role</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Status</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Quotes</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Revenue</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Last Active</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {filteredUsers.map((user) => (
                        <tr key={user.id} className="border-b border-white/10 hover:bg-white/5">
                          <td className="py-3 px-4">
                            <div>
                              <p className="text-white font-medium">{user.name}</p>
                              <p className="text-gray-400 text-sm">{user.email}</p>
                              <p className="text-gray-400 text-sm">{user.phone}</p>
                            </div>
                          </td>
                          <td className="py-3 px-4">
                            <Badge
                              variant={
                                user.role === "admin" ? "destructive" : user.role === "agent" ? "default" : user.role === "customer" ? "secondary" : "default"
                              }
                            >
                              {user.role}
                            </Badge>
                          </td>
                          <td className="py-3 px-4">
                            <Badge
                              variant={
                                user.status === "active"
                                  ? "default"
                                  : user.status === "pending"
                                    ? "secondary"
                                    : "destructive"
                              }
                            >
                              {user.status}
                            </Badge>
                          </td>
                          <td className="py-3 px-4 text-white">{user.quotesCount}</td>
                          <td className="py-3 px-4 text-white">₦{user.totalSpent.toLocaleString()}</td>
                          <td className="py-3 px-4 text-gray-300">{user.lastActive}</td>
                          <td className="py-3 px-4">
                            <div className="flex items-center space-x-2">
                              <Button size="sm" variant="ghost" className="text-blue-400 hover:bg-blue-500/10">
                                <Eye className="w-4 h-4" />
                              </Button>
                              <Button size="sm" variant="ghost" className="text-green-400 hover:bg-green-500/10">
                                <Edit className="w-4 h-4" />
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                className="text-red-400 hover:bg-red-500/10"
                                onClick={() => handleDeleteUser(user.id)}
                              >
                                <Trash2 className="w-4 h-4" />
                              </Button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          <TabsContent value="customers" className="space-y-6">
            <Card className="bg-white/10 backdrop-blur-lg border-white/20">
              <CardHeader>
                <CardTitle className="text-white">Customer Quotes & Leads</CardTitle>
                <CardDescription className="text-gray-300">Manage customer quotes and follow-ups</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr className="border-b border-white/20">
                        <th className="text-left py-3 px-4 text-white font-semibold">Customer</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Company</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Insurance Type</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Quote Status</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Amount</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Last Contact</th>
                        <th className="text-left py-3 px-4 text-white font-semibold">Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {customers.map((customer) => (
                        <tr key={customer.id} className="border-b border-white/10 hover:bg-white/5">
                          <td className="py-3 px-4">
                            <div>
                              <p className="text-white font-medium">{customer.name}</p>
                              <p className="text-gray-400 text-sm">{customer.email}</p>
                              <p className="text-gray-400 text-sm">{customer.phone}</p>
                            </div>
                          </td>
                          <td className="py-3 px-4 text-white">{customer.company || "Individual"}</td>
                          <td className="py-3 px-4 text-white">{customer.insuranceType}</td>
                          <td className="py-3 px-4">
                            <Badge
                              variant={
                                customer.quoteStatus === "approved"
                                  ? "default"
                                  : customer.quoteStatus === "pending"
                                    ? "secondary"
                                    : customer.quoteStatus === "rejected"
                                      ? "destructive"
                                      : "outline"
                              }
                            >
                              {customer.quoteStatus}
                            </Badge>
                          </td>
                          <td className="py-3 px-4 text-white">₦{customer.quoteAmount.toLocaleString()}</td>
                          <td className="py-3 px-4 text-gray-300">{customer.lastContact}</td>
                          <td className="py-3 px-4">
                            <div className="flex items-center space-x-2">
                              <Button size="sm" variant="ghost" className="text-blue-400 hover:bg-blue-500/10">
                                <Mail className="w-4 h-4" />
                              </Button>
                              <Button size="sm" variant="ghost" className="text-green-400 hover:bg-green-500/10">
                                <Phone className="w-4 h-4" />
                              </Button>
                              <Button size="sm" variant="ghost" className="text-purple-400 hover:bg-purple-500/10">
                                <MoreHorizontal className="w-4 h-4" />
                              </Button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </AdminLayout>
  )
}
