import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { 
  Users, 
  Plus, 
  Shield, 
  ShieldOff, 
  Key, 
  Loader2,
  AlertCircle,
  Check,
  X
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { useAuth } from '@/hooks/useAuth';
import { useToast } from '@/hooks/use-toast';
import { supabase } from '@/integrations/supabase/client';

const createUserSchema = z.object({
  email: z.string().email('Ogiltig e-postadress'),
  password: z.string().min(8, 'Lösenord måste vara minst 8 tecken'),
  role: z.enum(['admin', 'sales_team', 'user']),
});

type CreateUserFormData = z.infer<typeof createUserSchema>;

interface UserProfile {
  id: string;
  user_id: string;
  email: string;
  is_active: boolean;
  created_at: string;
  roles: string[];
}

export default function AdminUsers() {
  const [users, setUsers] = useState<UserProfile[]>([]);
  const [loading, setLoading] = useState(true);
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [showResetDialog, setShowResetDialog] = useState(false);
  const [selectedUser, setSelectedUser] = useState<UserProfile | null>(null);
  const [newPassword, setNewPassword] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  const navigate = useNavigate();
  const { user, isAdmin, loading: authLoading } = useAuth();
  const { toast } = useToast();

  const { register, handleSubmit, reset, setValue, formState: { errors } } = useForm<CreateUserFormData>({
    resolver: zodResolver(createUserSchema),
    defaultValues: {
      role: 'sales_team'
    }
  });

  useEffect(() => {
    if (!authLoading && !user) {
      navigate('/login');
    } else if (!authLoading && !isAdmin) {
      navigate('/dashboard/sales');
      toast({
        title: "Åtkomst nekad",
        description: "Du har inte behörighet att visa denna sida.",
        variant: "destructive"
      });
    }
  }, [user, isAdmin, authLoading, navigate, toast]);

  useEffect(() => {
    if (isAdmin) {
      fetchUsers();
    }
  }, [isAdmin]);

  const fetchUsers = async () => {
    setLoading(true);
    try {
      // Fetch profiles with their roles
      const { data: profiles, error: profilesError } = await supabase
        .from('profiles')
        .select('*')
        .order('created_at', { ascending: false });

      if (profilesError) throw profilesError;

      // Fetch all user roles
      const { data: allRoles, error: rolesError } = await supabase
        .from('user_roles')
        .select('user_id, role');

      if (rolesError) throw rolesError;

      // Combine profiles with roles
      const usersWithRoles: UserProfile[] = (profiles || []).map(profile => ({
        ...profile,
        roles: (allRoles || [])
          .filter(r => r.user_id === profile.user_id)
          .map(r => r.role)
      }));

      setUsers(usersWithRoles);
    } catch (error: any) {
      console.error('Error fetching users:', error);
      toast({
        title: "Fel",
        description: "Kunde inte hämta användare",
        variant: "destructive"
      });
    } finally {
      setLoading(false);
    }
  };

  const onCreateUser = async (data: CreateUserFormData) => {
    setIsSubmitting(true);
    try {
      // Call edge function to create user (requires admin privileges)
      const { data: result, error } = await supabase.functions.invoke('admin-create-user', {
        body: {
          email: data.email,
          password: data.password,
          role: data.role
        }
      });

      if (error) throw error;
      if (result?.error) throw new Error(result.error);

      toast({
        title: "Användare skapad",
        description: `${data.email} har lagts till med rollen ${data.role}`,
      });

      reset();
      setShowCreateDialog(false);
      fetchUsers();
    } catch (error: any) {
      console.error('Error creating user:', error);
      toast({
        title: "Fel",
        description: error.message || "Kunde inte skapa användare",
        variant: "destructive"
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  const toggleUserStatus = async (userProfile: UserProfile) => {
    try {
      const { error } = await supabase
        .from('profiles')
        .update({ is_active: !userProfile.is_active })
        .eq('id', userProfile.id);

      if (error) throw error;

      toast({
        title: userProfile.is_active ? "Användare inaktiverad" : "Användare aktiverad",
        description: `${userProfile.email} har ${userProfile.is_active ? 'inaktiverats' : 'aktiverats'}`,
      });

      fetchUsers();
    } catch (error: any) {
      console.error('Error toggling user status:', error);
      toast({
        title: "Fel",
        description: "Kunde inte ändra användarstatus",
        variant: "destructive"
      });
    }
  };

  const resetPassword = async () => {
    if (!selectedUser || !newPassword) return;
    
    setIsSubmitting(true);
    try {
      // Call edge function to reset password
      const { data: result, error } = await supabase.functions.invoke('admin-reset-password', {
        body: {
          userId: selectedUser.user_id,
          newPassword: newPassword
        }
      });

      if (error) throw error;
      if (result?.error) throw new Error(result.error);

      toast({
        title: "Lösenord återställt",
        description: `Lösenordet för ${selectedUser.email} har uppdaterats`,
      });

      setNewPassword('');
      setShowResetDialog(false);
      setSelectedUser(null);
    } catch (error: any) {
      console.error('Error resetting password:', error);
      toast({
        title: "Fel",
        description: error.message || "Kunde inte återställa lösenord",
        variant: "destructive"
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  if (authLoading || loading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (!isAdmin) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-6">
        <div className="text-center">
          <AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
          <h1 className="text-2xl font-bold text-foreground mb-2">Åtkomst nekad</h1>
          <p className="text-muted-foreground">Du har inte behörighet att visa denna sida.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="container mx-auto px-4 py-8">
         <div className="flex flex-wrap items-center justify-between gap-4 mb-8">
          <div>
            <h1 className="text-2xl font-bold text-foreground flex items-center gap-3">
              <Users className="h-7 w-7" />
              Användarhantering
            </h1>
            <p className="text-muted-foreground mt-1">
              Hantera användare och deras behörigheter
            </p>
          </div>
          <Button onClick={() => setShowCreateDialog(true)}>
            <Plus className="h-4 w-4 mr-2" />
            Ny användare
          </Button>
        </div>

         <div className="bg-card border border-border rounded-md max-w-full overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>E-post</TableHead>
                <TableHead>Roll</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Skapad</TableHead>
                <TableHead className="text-right">Åtgärder</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {users.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                    Inga användare hittades
                  </TableCell>
                </TableRow>
              ) : (
                users.map((userProfile) => (
                  <TableRow key={userProfile.id}>
                    <TableCell className="font-medium">{userProfile.email}</TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-1">
                        {userProfile.roles.map((role) => (
                          <Badge 
                            key={role} 
                            variant={role === 'admin' ? 'default' : 'secondary'}
                          >
                            {role === 'admin' ? 'Admin' : role === 'sales_team' ? 'Säljteam' : 'Användare'}
                          </Badge>
                        ))}
                        {userProfile.roles.length === 0 && (
                          <Badge variant="outline">Ingen roll</Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      {userProfile.is_active ? (
                        <Badge variant="default" className="bg-green-600">
                          <Check className="h-3 w-3 mr-1" />
                          Aktiv
                        </Badge>
                      ) : (
                        <Badge variant="destructive">
                          <X className="h-3 w-3 mr-1" />
                          Inaktiv
                        </Badge>
                      )}
                    </TableCell>
                    <TableCell className="text-muted-foreground">
                      {new Date(userProfile.created_at).toLocaleDateString('sv-SE')}
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => {
                            setSelectedUser(userProfile);
                            setShowResetDialog(true);
                          }}
                        >
                          <Key className="h-4 w-4 mr-1" />
                          Lösenord
                        </Button>
                        <Button
                          variant={userProfile.is_active ? "destructive" : "default"}
                          size="sm"
                          onClick={() => toggleUserStatus(userProfile)}
                        >
                          {userProfile.is_active ? (
                            <>
                              <ShieldOff className="h-4 w-4 mr-1" />
                              Inaktivera
                            </>
                          ) : (
                            <>
                              <Shield className="h-4 w-4 mr-1" />
                              Aktivera
                            </>
                          )}
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>

        {/* Back to dashboard link */}
        <div className="mt-6">
          <Button variant="ghost" onClick={() => navigate('/dashboard/sales')}>
            ← Tillbaka till CRM
          </Button>
        </div>
      </div>

      {/* Create User Dialog */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Skapa ny användare</DialogTitle>
            <DialogDescription>
              Fyll i uppgifterna för den nya användaren
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit(onCreateUser)} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email">E-post</Label>
              <Input
                id="email"
                type="email"
                {...register('email')}
                placeholder="anvandare@exempel.se"
              />
              {errors.email && (
                <p className="text-xs text-destructive">{errors.email.message}</p>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">Lösenord</Label>
              <Input
                id="password"
                type="password"
                {...register('password')}
                placeholder="Minst 8 tecken"
              />
              {errors.password && (
                <p className="text-xs text-destructive">{errors.password.message}</p>
              )}
            </div>
            <div className="space-y-2">
              <Label htmlFor="role">Roll</Label>
              <Select 
                defaultValue="sales_team"
                onValueChange={(value) => setValue('role', value as any)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Välj roll" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="admin">Admin</SelectItem>
                  <SelectItem value="sales_team">Säljteam</SelectItem>
                  <SelectItem value="user">Användare</SelectItem>
                </SelectContent>
              </Select>
              {errors.role && (
                <p className="text-xs text-destructive">{errors.role.message}</p>
              )}
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setShowCreateDialog(false)}>
                Avbryt
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Skapar...
                  </>
                ) : (
                  'Skapa användare'
                )}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Reset Password Dialog */}
      <Dialog open={showResetDialog} onOpenChange={setShowResetDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Återställ lösenord</DialogTitle>
            <DialogDescription>
              Ange ett nytt lösenord för {selectedUser?.email}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="newPassword">Nytt lösenord</Label>
              <Input
                id="newPassword"
                type="password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder="Minst 8 tecken"
              />
            </div>
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => {
              setShowResetDialog(false);
              setNewPassword('');
              setSelectedUser(null);
            }}>
              Avbryt
            </Button>
            <Button 
              onClick={resetPassword} 
              disabled={isSubmitting || newPassword.length < 8}
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Återställer...
                </>
              ) : (
                'Återställ lösenord'
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
