"use client";

import { useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Loader2, UserPlus } from "lucide-react";
import { toast } from "sonner";

const roleLabels: Record<string, string> = { owner: "Propietario", admin: "Admin", doctor: "Doctor", receptionist: "Recepcionista" };
const roleColors: Record<string, string> = { owner: "bg-violet-100 text-violet-700", admin: "bg-blue-100 text-blue-700", doctor: "bg-emerald-100 text-emerald-700", receptionist: "bg-gray-100 text-gray-700" };

interface Props {
  users: any[];
  currentUserId: string;
}

export function UsersList({ users, currentUserId }: Props) {
  const supabase = createClient();
  const [showDialog, setShowDialog] = useState(false);
  const [loading, setLoading] = useState(false);

  async function handleAddUser(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    const form = new FormData(e.currentTarget);
    const email = form.get("email") as string;
    const password = form.get("password") as string;
    const fullName = form.get("full_name") as string;
    const role = form.get("role") as string;
    const specialty = (form.get("specialty") as string) || null;

    // Get current user's clinic
    const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", currentUserId).single();
    if (!profile) { toast.error("Error de perfil"); setLoading(false); return; }

    // Sign up the new user (this creates auth.users entry)
    const { data: authData, error: authErr } = await supabase.auth.signUp({ email, password });
    if (authErr || !authData.user) { toast.error(authErr?.message || "Error al crear usuario"); setLoading(false); return; }

    // Create user profile
    const { error: profileErr } = await supabase.from("users").insert({
      id: authData.user.id,
      clinic_id: profile.clinic_id,
      full_name: fullName,
      email,
      role,
      specialty,
    });

    if (profileErr) { toast.error(profileErr.message); setLoading(false); return; }

    toast.success(`${fullName} agregado como ${roleLabels[role]}`);
    setLoading(false);
    setShowDialog(false);
    window.location.reload();
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <Button onClick={() => setShowDialog(true)} className="gap-2"><UserPlus className="h-4 w-4" /> Agregar usuario</Button>
      </div>

      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>Usuario</TableHead>
              <TableHead>Email</TableHead>
              <TableHead>Rol</TableHead>
              <TableHead>Especialidad</TableHead>
              <TableHead>Estado</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {users.map((u: any) => (
              <TableRow key={u.id}>
                <TableCell>
                  <div className="flex items-center gap-3">
                    <Avatar className="h-8 w-8">
                      <AvatarFallback className="bg-primary/10 text-primary text-xs font-semibold">
                        {u.full_name?.split(" ").map((n: string) => n[0]).join("").slice(0, 2)}
                      </AvatarFallback>
                    </Avatar>
                    <span className="font-medium">{u.full_name}</span>
                    {u.id === currentUserId && <Badge variant="outline" className="text-[10px]">Tu</Badge>}
                  </div>
                </TableCell>
                <TableCell className="text-muted-foreground text-sm">{u.email}</TableCell>
                <TableCell><Badge className={roleColors[u.role]} variant="secondary">{roleLabels[u.role]}</Badge></TableCell>
                <TableCell className="text-muted-foreground text-sm">{u.specialty || "—"}</TableCell>
                <TableCell>{u.is_active ? <Badge variant="outline" className="text-emerald-600">Activo</Badge> : <Badge variant="outline" className="text-red-600">Inactivo</Badge>}</TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </Card>

      {/* Add User Dialog */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader><DialogTitle>Agregar usuario</DialogTitle></DialogHeader>
          <form onSubmit={handleAddUser} className="space-y-4">
            <div className="space-y-2"><Label>Nombre completo *</Label><Input name="full_name" required className="h-10" placeholder="Dr. Ana Garcia" /></div>
            <div className="space-y-2"><Label>Email *</Label><Input name="email" type="email" required className="h-10" placeholder="ana@clinica.com" /></div>
            <div className="space-y-2"><Label>Contrasena *</Label><Input name="password" type="password" required minLength={6} className="h-10" placeholder="Minimo 6 caracteres" /></div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2">
                <Label>Rol *</Label>
                <Select name="role" defaultValue="doctor">
                  <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="doctor">Doctor</SelectItem>
                    <SelectItem value="receptionist">Recepcionista</SelectItem>
                    <SelectItem value="admin">Admin</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2"><Label>Especialidad</Label><Input name="specialty" className="h-10" placeholder="Medicina general" /></div>
            </div>
            <Button type="submit" disabled={loading} className="w-full h-10">
              {loading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Agregando...</> : "Agregar usuario"}
            </Button>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
