import { useRef, useState } from "react";
import { Plus, Upload, Pencil, Trash2, UserCheck, UserX, Users, AlertCircle } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  useListUsers,
  useCreateUser,
  useUpdateUser,
  useDeleteUser,
  useImportUsers,
  type UserPayload,
  type ImportResult,
} from "@/api/users";
import { UserForm } from "@/components/UserForm";
import type { User } from "@/types/api";

const roleVariant: Record<string, "default" | "secondary" | "outline" | "warning"> = {
  admin: "default",
  manager: "secondary",
  user: "outline",
  auditor: "warning",
};

// ─── CSV parsing ──────────────────────────────────────────────────────────────

function parseCSV(text: string): UserPayload[] {
  const lines = text.trim().split(/\r?\n/);
  if (lines.length < 2) return [];

  const headers = lines[0].split(",").map((h) => h.trim().toLowerCase());
  const hasFirstLast = headers.includes("first_name") && headers.includes("last_name");

  return lines.slice(1).flatMap((line) => {
    const cols = line.split(",").map((c) => c.trim().replace(/^"|"$/g, ""));
    const get = (key: string) => cols[headers.indexOf(key)] ?? "";

    const email = get("email");
    if (!email) return [];

    const name = hasFirstLast
      ? `${get("first_name")} ${get("last_name")}`.trim()
      : get("name");

    return [{
      email,
      name: name || email,
      department: get("department"),
      role: get("role") || "user",
      is_active: true,
    }];
  });
}

// ─── Component ────────────────────────────────────────────────────────────────

export function UsersPage() {
  const [formOpen, setFormOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | undefined>();
  const [importResult, setImportResult] = useState<ImportResult | null>(null);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const csvInputRef = useRef<HTMLInputElement>(null);

  const { data: users = [], isLoading } = useListUsers();
  const createMutation = useCreateUser();
  const updateMutation = useUpdateUser();
  const deleteMutation = useDeleteUser();
  const importMutation = useImportUsers();

  const activeCount = users.filter((u) => u.is_active).length;
  const inactiveCount = users.length - activeCount;

  const handleSubmit = async (payload: UserPayload) => {
    try {
      if (editingUser) {
        await updateMutation.mutateAsync({ id: editingUser.id, ...payload });
      } else {
        await createMutation.mutateAsync(payload);
      }
      setFormOpen(false);
      setEditingUser(undefined);
      setErrorMsg(null);
    } catch (e) {
      setErrorMsg(e instanceof Error ? e.message : "Une erreur est survenue");
    }
  };

  const handleEdit = (user: User) => {
    setEditingUser(user);
    setFormOpen(true);
  };

  const handleOpenCreate = () => {
    setEditingUser(undefined);
    setFormOpen(true);
  };

  const handleToggleActive = (user: User) => {
    setErrorMsg(null);
    updateMutation.mutate(
      { id: user.id, email: user.email, name: user.name, department: user.department, role: user.role, is_active: !user.is_active },
      { onError: (e) => setErrorMsg(e instanceof Error ? e.message : "Erreur lors de la mise à jour") }
    );
  };

  const handleDelete = (user: User) => {
    if (confirm(`Supprimer définitivement "${user.name}" (${user.email}) ?`)) {
      setErrorMsg(null);
      deleteMutation.mutate(user.id, {
        onError: (e) => setErrorMsg(e instanceof Error ? e.message : "Erreur lors de la suppression"),
      });
    }
  };

  const handleCSVFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    e.target.value = "";
    setErrorMsg(null);
    setImportResult(null);

    const text = await file.text();
    const rows = parseCSV(text);
    if (rows.length === 0) {
      setErrorMsg("Aucun utilisateur trouvé dans le fichier. Format attendu : email,name,department,role ou email,first_name,last_name,department,role");
      return;
    }

    try {
      const result = await importMutation.mutateAsync(rows);
      setImportResult(result);
    } catch (e) {
      setErrorMsg(e instanceof Error ? e.message : "Erreur lors de l'import");
    }
  };

  const isPending = createMutation.isPending || updateMutation.isPending;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold">Utilisateurs</h2>
          <p className="text-sm text-muted-foreground">Gérez les accès et les rôles des utilisateurs</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={() => csvInputRef.current?.click()} disabled={importMutation.isPending}>
            <Upload className="h-4 w-4 mr-2" />
            {importMutation.isPending ? "Import en cours..." : "Importer CSV"}
          </Button>
          <input
            ref={csvInputRef}
            type="file"
            accept=".csv,text/csv"
            className="hidden"
            onChange={handleCSVFile}
          />
          <Button onClick={handleOpenCreate}>
            <Plus className="h-4 w-4 mr-2" />
            Nouvel utilisateur
          </Button>
        </div>
      </div>

      {/* Error banner */}
      {errorMsg && (
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription className="flex items-center justify-between">
            <span>{errorMsg}</span>
            <button className="ml-4 opacity-60 hover:opacity-100" onClick={() => setErrorMsg(null)}>✕</button>
          </AlertDescription>
        </Alert>
      )}

      {/* Import result banner */}
      {importResult && (
        <div className={`rounded-lg border p-3 text-sm flex items-center justify-between ${importResult.failed === 0 ? "bg-green-50 border-green-200 text-green-800" : "bg-yellow-50 border-yellow-200 text-yellow-800"}`}>
          <span>
            Import terminé — <strong>{importResult.success}</strong> créé(s)
            {importResult.failed > 0 && <>, <strong>{importResult.failed}</strong> échoué(s) : {importResult.errors.join(", ")}</>}
          </span>
          <button className="ml-4 opacity-60 hover:opacity-100" onClick={() => setImportResult(null)}>✕</button>
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-3 gap-4">
        <div className="rounded-lg border bg-card p-4 flex items-center gap-3">
          <Users className="h-8 w-8 text-muted-foreground" />
          <div>
            <p className="text-2xl font-bold">{isLoading ? "—" : users.length}</p>
            <p className="text-xs text-muted-foreground">Total</p>
          </div>
        </div>
        <div className="rounded-lg border bg-card p-4 flex items-center gap-3">
          <UserCheck className="h-8 w-8 text-green-600" />
          <div>
            <p className="text-2xl font-bold">{isLoading ? "—" : activeCount}</p>
            <p className="text-xs text-muted-foreground">Actifs</p>
          </div>
        </div>
        <div className="rounded-lg border bg-card p-4 flex items-center gap-3">
          <UserX className="h-8 w-8 text-muted-foreground" />
          <div>
            <p className="text-2xl font-bold">{isLoading ? "—" : inactiveCount}</p>
            <p className="text-xs text-muted-foreground">Inactifs</p>
          </div>
        </div>
      </div>

      {/* Table */}
      {isLoading ? (
        <div className="space-y-2">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-14 w-full" />
          ))}
        </div>
      ) : (
        <div className="rounded-lg border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Nom</TableHead>
                <TableHead>Département</TableHead>
                <TableHead>Rôle</TableHead>
                <TableHead>Statut</TableHead>
                <TableHead>Créé le</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {users.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground py-10">
                    Aucun utilisateur — créez-en un ou importez un CSV.
                  </TableCell>
                </TableRow>
              ) : (
                users.map((user) => (
                  <TableRow key={user.id} className={!user.is_active ? "opacity-50" : undefined}>
                    <TableCell>
                      <div>
                        <p className="font-medium text-sm">{user.name}</p>
                        <p className="text-xs text-muted-foreground">{user.email}</p>
                      </div>
                    </TableCell>
                    <TableCell className="text-sm">{user.department || "—"}</TableCell>
                    <TableCell>
                      <Badge variant={roleVariant[user.role] ?? "outline"} className="capitalize">
                        {user.role}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <button
                        onClick={() => handleToggleActive(user)}
                        disabled={updateMutation.isPending}
                        title={user.is_active ? "Désactiver" : "Réactiver"}
                        className="cursor-pointer"
                      >
                        <Badge variant={user.is_active ? "success" : "secondary"}>
                          {user.is_active ? "Actif" : "Inactif"}
                        </Badge>
                      </button>
                    </TableCell>
                    <TableCell className="text-sm text-muted-foreground">
                      {new Date(user.created_at).toLocaleDateString("fr-FR")}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-1">
                        <Button variant="ghost" size="icon" onClick={() => handleEdit(user)} title="Modifier">
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDelete(user)}
                          disabled={deleteMutation.isPending}
                          title="Supprimer"
                        >
                          <Trash2 className="h-4 w-4 text-destructive" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      )}

      <UserForm
        open={formOpen}
        onOpenChange={(open) => {
          setFormOpen(open);
          if (!open) setEditingUser(undefined);
        }}
        user={editingUser}
        onSubmit={handleSubmit}
        isPending={isPending}
      />
    </div>
  );
}
