import { useState } from "react";
import { Link } from "react-router";
import {
  UserPlus,
  Eye,
  Search,
  Download,
  Mail,
  Shield,
  Ban,
  CheckCircle,
  XCircle,
  Clock,
  TrendingUp,
  Users as UsersIcon,
  MoreVertical,
  Edit,
  Trash2,
} from "lucide-react";
import { ProtectedRoute } from "~/components/protected-route";
import { Header } from "~/components/header";
import { Button } from "~/components/ui/button/button";
import { Input } from "~/components/ui/input/input";
import { Label } from "~/components/ui/label/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "~/components/ui/table/table";
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card/card";
import { Badge } from "~/components/ui/badge/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "~/components/ui/dialog/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select/select";
import { mockUsers, type VPNUser } from "~/data/users";
import styles from "./users.module.css";

export default function UsersAdvanced() {
  const [users, setUsers] = useState<VPNUser[]>(mockUsers);
  const [showForm, setShowForm] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterStatus, setFilterStatus] = useState<"all" | "active" | "inactive">("all");
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    server: "vpn-us-east-01.company.com",
    protocol: "OpenVPN",
  });
  const [successMessage, setSuccessMessage] = useState("");

  // فیلتر کاربران
  const filteredUsers = users.filter((user) => {
    const matchesSearch =
      user.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      user.email.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === "all" || user.status === filterStatus;
    return matchesSearch && matchesStatus;
  });

  // آمار کاربران
  const stats = {
    total: users.length,
    active: users.filter((u) => u.status === "active").length,
    inactive: users.filter((u) => u.status === "inactive").length,
    newThisMonth: Math.floor(users.length * 0.23),
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const newUser: VPNUser = {
      id: String(users.length + 1),
      name: formData.name,
      email: formData.email,
      status: "active",
      createdAt: new Date().toISOString().split("T")[0],
      lastActive: new Date().toISOString().split("T")[0],
      vpnConfig: {
        username: formData.email.split("@")[0],
        server: formData.server,
        protocol: formData.protocol,
        port: formData.protocol === "OpenVPN" ? 1194 : 51820,
        configKey: generateConfigKey(),
      },
    };

    setUsers([...users, newUser]);
    setFormData({ name: "", email: "", server: "vpn-us-east-01.company.com", protocol: "OpenVPN" });
    setShowForm(false);
    setSuccessMessage(`کاربر "${newUser.name}" با موفقیت ایجاد شد.`);
    setTimeout(() => setSuccessMessage(""), 5000);
  };

  const generateConfigKey = () => {
    const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return Array.from({ length: 20 }, () => chars[Math.floor(Math.random() * chars.length)]).join("");
  };

  const exportUsers = () => {
    const csv = [
      ["نام", "ایمیل", "وضعیت", "سرور", "پروتکل", "تاریخ ایجاد"].join(","),
      ...filteredUsers.map((u) =>
        [u.name, u.email, u.status, u.vpnConfig.server, u.vpnConfig.protocol, u.createdAt].join(",")
      ),
    ].join("\n");

    const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8;" });
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = `users_${new Date().toISOString().split("T")[0]}.csv`;
    link.click();
  };

  const sendEmailToAll = () => {
    alert("قابلیت ارسال ایمیل گروهی به تمام کاربران");
  };

  const toggleUserStatus = (userId: string) => {
    setUsers(users.map((u) => (u.id === userId ? { ...u, status: u.status === "active" ? "inactive" : "active" } : u)));
  };

  const deleteUser = (userId: string) => {
    if (confirm("آیا از حذف این کاربر اطمینان دارید؟")) {
      setUsers(users.filter((u) => u.id !== userId));
    }
  };

  return (
    <ProtectedRoute>
      <div className={styles.container}>
        <Header />
        <main className={styles.content}>
          {/* آمار کلی */}
          <div className={styles.statsGrid}>
            <Card className={styles.statCard}>
              <CardContent className={styles.statContent}>
                <div className={styles.statIcon} style={{ background: "var(--color-accent-3)" }}>
                  <UsersIcon size={24} style={{ color: "var(--color-accent-11)" }} />
                </div>
                <div className={styles.statInfo}>
                  <p className={styles.statLabel}>کل کاربران</p>
                  <h3 className={styles.statValue}>{stats.total}</h3>
                </div>
              </CardContent>
            </Card>

            <Card className={styles.statCard}>
              <CardContent className={styles.statContent}>
                <div className={styles.statIcon} style={{ background: "var(--color-success-3)" }}>
                  <CheckCircle size={24} style={{ color: "var(--color-success-11)" }} />
                </div>
                <div className={styles.statInfo}>
                  <p className={styles.statLabel}>کاربران فعال</p>
                  <h3 className={styles.statValue}>{stats.active}</h3>
                </div>
              </CardContent>
            </Card>

            <Card className={styles.statCard}>
              <CardContent className={styles.statContent}>
                <div className={styles.statIcon} style={{ background: "var(--color-error-3)" }}>
                  <XCircle size={24} style={{ color: "var(--color-error-11)" }} />
                </div>
                <div className={styles.statInfo}>
                  <p className={styles.statLabel}>کاربران غیرفعال</p>
                  <h3 className={styles.statValue}>{stats.inactive}</h3>
                </div>
              </CardContent>
            </Card>

            <Card className={styles.statCard}>
              <CardContent className={styles.statContent}>
                <div className={styles.statIcon} style={{ background: "var(--color-info-3)" }}>
                  <TrendingUp size={24} style={{ color: "var(--color-info-11)" }} />
                </div>
                <div className={styles.statInfo}>
                  <p className={styles.statLabel}>کاربران جدید (ماه جاری)</p>
                  <h3 className={styles.statValue}>{stats.newThisMonth}</h3>
                </div>
              </CardContent>
            </Card>
          </div>

          <div className={styles.pageHeader}>
            <div className={styles.headerContent}>
              <h1 className={styles.pageTitle}>مدیریت پیشرفته کاربران</h1>
              <p className={styles.pageDescription}>مدیریت حساب‌های کاربری VPN با امکانات پیشرفته</p>
            </div>
            <div className={styles.headerActions}>
              <Button variant="outline" onClick={exportUsers}>
                <Download size={16} style={{ marginLeft: "var(--space-2)" }} />
                Export CSV
              </Button>
              <Button variant="outline" onClick={sendEmailToAll}>
                <Mail size={16} style={{ marginLeft: "var(--space-2)" }} />
                ایمیل گروهی
              </Button>
              <Button onClick={() => setShowForm(!showForm)}>
                <UserPlus style={{ width: "16px", height: "16px", marginLeft: "var(--space-2)" }} />
                {showForm ? "لغو" : "افزودن کاربر"}
              </Button>
            </div>
          </div>

          {successMessage && <div className={styles.success}>{successMessage}</div>}

          {/* فرم افزودن کاربر */}
          {showForm && (
            <Card className={styles.addUserCard}>
              <CardHeader>
                <CardTitle>افزودن کاربر جدید</CardTitle>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleSubmit} className={styles.form}>
                  <div className={styles.formRow}>
                    <div className={styles.formGroup}>
                      <Label htmlFor="name">نام کامل</Label>
                      <Input
                        id="name"
                        value={formData.name}
                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                        placeholder="علی احمدی"
                        required
                      />
                    </div>

                    <div className={styles.formGroup}>
                      <Label htmlFor="email">آدرس ایمیل</Label>
                      <Input
                        id="email"
                        type="email"
                        value={formData.email}
                        onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                        placeholder="ali@example.com"
                        required
                      />
                    </div>
                  </div>

                  <div className={styles.formRow}>
                    <div className={styles.formGroup}>
                      <Label htmlFor="server">سرور VPN</Label>
                      <select
                        id="server"
                        value={formData.server}
                        onChange={(e) => setFormData({ ...formData, server: e.target.value })}
                        className={styles.select}
                      >
                        <option value="vpn-us-east-01.company.com">آمریکا شرقی</option>
                        <option value="vpn-us-west-01.company.com">آمریکا غربی</option>
                        <option value="vpn-eu-west-01.company.com">اروپا غربی</option>
                        <option value="vpn-asia-01.company.com">آسیا</option>
                      </select>
                    </div>

                    <div className={styles.formGroup}>
                      <Label htmlFor="protocol">پروتکل</Label>
                      <select
                        id="protocol"
                        value={formData.protocol}
                        onChange={(e) => setFormData({ ...formData, protocol: e.target.value })}
                        className={styles.select}
                      >
                        <option value="OpenVPN">OpenVPN</option>
                        <option value="WireGuard">WireGuard</option>
                      </select>
                    </div>
                  </div>

                  <div className={styles.formActions}>
                    <Button type="submit">ایجاد کاربر</Button>
                    <Button type="button" variant="outline" onClick={() => setShowForm(false)}>
                      لغو
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          )}

          {/* فیلتر و جستجو */}
          <Card className={styles.filterCard}>
            <CardContent className={styles.filterContent}>
              <div className={styles.searchBox}>
                <Search size={18} className={styles.searchIcon} />
                <Input
                  type="text"
                  placeholder="جستجو بر اساس نام یا ایمیل..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className={styles.searchInput}
                />
              </div>
              <div className={styles.filterButtons}>
                <Button variant={filterStatus === "all" ? "default" : "outline"} size="sm" onClick={() => setFilterStatus("all")}>
                  همه ({stats.total})
                </Button>
                <Button
                  variant={filterStatus === "active" ? "default" : "outline"}
                  size="sm"
                  onClick={() => setFilterStatus("active")}
                >
                  <CheckCircle size={14} style={{ marginLeft: "6px" }} />
                  فعال ({stats.active})
                </Button>
                <Button
                  variant={filterStatus === "inactive" ? "default" : "outline"}
                  size="sm"
                  onClick={() => setFilterStatus("inactive")}
                >
                  <XCircle size={14} style={{ marginLeft: "6px" }} />
                  غیرفعال ({stats.inactive})
                </Button>
              </div>
            </CardContent>
          </Card>

          {/* جدول کاربران */}
          <div className={styles.userListSection}>
            <div className={styles.sectionHeader}>
              <h2 className={styles.sectionTitle}>نتایج جستجو ({filteredUsers.length} کاربر)</h2>
            </div>
            {filteredUsers.length === 0 ? (
              <Card>
                <CardContent className={styles.emptyState}>
                  <UsersIcon size={48} style={{ color: "var(--color-neutral-8)" }} />
                  <p>کاربری یافت نشد</p>
                </CardContent>
              </Card>
            ) : (
              <div className={styles.tableWrapper}>
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>نام</TableHead>
                      <TableHead>ایمیل</TableHead>
                      <TableHead>وضعیت</TableHead>
                      <TableHead>سرور</TableHead>
                      <TableHead>پروتکل</TableHead>
                      <TableHead>تاریخ ایجاد</TableHead>
                      <TableHead>آخرین فعالیت</TableHead>
                      <TableHead>عملیات</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredUsers.map((user) => (
                      <TableRow key={user.id}>
                        <TableCell style={{ fontWeight: 500 }}>{user.name}</TableCell>
                        <TableCell>{user.email}</TableCell>
                        <TableCell>
                          <Badge
                            variant={user.status === "active" ? "default" : "secondary"}
                            style={{
                              background: user.status === "active" ? "var(--color-success-3)" : "var(--color-neutral-3)",
                              color: user.status === "active" ? "var(--color-success-11)" : "var(--color-neutral-11)",
                            }}
                          >
                            {user.status === "active" ? (
                              <CheckCircle size={12} style={{ marginLeft: "4px" }} />
                            ) : (
                              <XCircle size={12} style={{ marginLeft: "4px" }} />
                            )}
                            {user.status === "active" ? "فعال" : "غیرفعال"}
                          </Badge>
                        </TableCell>
                        <TableCell>{user.vpnConfig.server.split(".")[0]}</TableCell>
                        <TableCell>
                          <Badge variant="outline">{user.vpnConfig.protocol}</Badge>
                        </TableCell>
                        <TableCell>{user.createdAt}</TableCell>
                        <TableCell>
                          <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>
                            <Clock size={14} style={{ color: "var(--color-neutral-9)" }} />
                            {user.lastActive}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className={styles.actions}>
                            <Link to={`/users/${user.id}`}>
                              <Button variant="outline" size="sm">
                                <Eye size={14} style={{ marginLeft: "6px" }} />
                                مشاهده
                              </Button>
                            </Link>
                            <Button variant="outline" size="sm" onClick={() => toggleUserStatus(user.id)}>
                              {user.status === "active" ? (
                                <Ban size={14} style={{ marginLeft: "6px" }} />
                              ) : (
                                <Shield size={14} style={{ marginLeft: "6px" }} />
                              )}
                              {user.status === "active" ? "غیرفعال" : "فعال"}
                            </Button>
                            <Button variant="outline" size="sm" onClick={() => deleteUser(user.id)}>
                              <Trash2 size={14} style={{ marginLeft: "6px", color: "var(--color-error-9)" }} />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}
          </div>
        </main>
      </div>
    </ProtectedRoute>
  );
}
