import { useState, useEffect } from "react";
import { apiFetch } from '@/utils/api';
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { 
  Form, 
  FormControl, 
  FormDescription, 
  FormField, 
  FormItem, 
  FormLabel, 
  FormMessage 
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { PermissionSelector } from "./PermissionSelector";
import { Alert, AlertDescription } from "@/components/ui/alert";
import config from "@/config";

interface Permission {
  id: number;
  name: string;
  code: string;
  description?: string;
  category?: string;
}

interface RocketChatUser {
  id: number;
  username: string;
  name: string;
  type: string;
  active: boolean;
  mongo_id?: string;
}

interface User {
  id: number;
  username: string;
  email?: string;
  is_admin: boolean;
  is_active: boolean;
  rocket_chat_user_id?: number;
  permissions?: Permission[];
}

interface PermissionCategory {
  category: string;
  permissions: Permission[];
}

interface UserFormProps {
  user: User | null;
  permissions: PermissionCategory[];
  onSave: (userData: any) => void;
  onCancel: () => void;
}

// Form validation schema
const userFormSchema = z.object({
  username: z.string().min(3, { message: "Username must be at least 3 characters" }),
  email: z.string().email({ message: "Please enter a valid email" }).optional().or(z.literal("")),
  password: z.string().min(6, { message: "Password must be at least 6 characters" }).optional().or(z.literal("")),
  is_admin: z.boolean().default(false),
  is_active: z.boolean().default(true),
  rocket_chat_user_id: z.string().default("none"),
});

type FormValues = z.infer<typeof userFormSchema>;

// Helper function to get all permission IDs from all categories
const getAllPermissionIds = (permissionCategories: PermissionCategory[]): number[] => {
  const allIds: number[] = [];
  
  if (permissionCategories && permissionCategories.length > 0) {
    permissionCategories.forEach(category => {
      category.permissions.forEach(permission => {
        allIds.push(permission.id);
      });
    });
  }
  
  return allIds;
};

// User save data interface (represents the data structure for saving users)
interface UserSaveData {
  id?: number;
  username: string;
  email?: string;
  password?: string;
  is_admin: boolean;
  is_active: boolean;
  rocket_chat_user_id?: number;
  permissions: Permission[];
}

export function UserForm({ user, permissions, onSave, onCancel }: UserFormProps) {
  const [selectedPermissions, setSelectedPermissions] = useState<number[]>([]);
  const [formError, setFormError] = useState<string | null>(null);
  const [rocketChatUsers, setRocketChatUsers] = useState<RocketChatUser[]>([]);
  const [loadingRocketChatUsers, setLoadingRocketChatUsers] = useState(true);
  
  // Initialize the form with React Hook Form
  const form = useForm<FormValues>({
    resolver: zodResolver(userFormSchema),
    defaultValues: {
      username: user?.username || "",
      email: user?.email || "",
      password: "", // Don't pre-fill password
      is_admin: user?.is_admin || false,
      is_active: user?.is_active !== false,
      // Convert number to string for Select, default to "none"
      rocket_chat_user_id: user?.rocket_chat_user_id ? user.rocket_chat_user_id.toString() : "none",
    },
  });
  
  // Fetch Rocket Chat users
  useEffect(() => {
    const fetchRocketChatUsers = async () => {
      try {
        const response = await apiFetch(`${config.chatUrl}/users`);
        const data = await response.json();
        
        if (data.status === 'success') {
          setRocketChatUsers(data.users);
        } else {
          console.error('Failed to fetch Rocket Chat users:', data.error);
        }
      } catch (error) {
        console.error('Error fetching Rocket Chat users:', error);
      } finally {
        setLoadingRocketChatUsers(false);
      }
    };

    // Ensure rocket_chat_user_id is set to "none" initially if not set
    if (!form.getValues().rocket_chat_user_id) {
      form.setValue('rocket_chat_user_id', 'none');
    }

    fetchRocketChatUsers();
  }, [form]);

  // Initialize selected permissions and form values
  useEffect(() => {
    
    if (user?.permissions && Array.isArray(user.permissions) && user.permissions.length > 0) {
      // Extract IDs from the permissions
      const permissionIds = user.permissions.map(p => p.id);
     
      setSelectedPermissions(permissionIds);
    } else {
     
      setSelectedPermissions([]);
    }

    // Update form values when user data changes
    if (user) {
      form.reset({
        username: user.username || "",
        email: user.email || "",
        password: "", // Don't pre-fill password
        is_admin: user.is_admin || false,
        is_active: user.is_active !== false,
        // Convert number to string for the Select component, or use "none" as default
        rocket_chat_user_id: user.rocket_chat_user_id ? user.rocket_chat_user_id.toString() : "none",
      });
    } else {
      // For new users, ensure rocket_chat_user_id defaults to "none"
      form.reset({
        username: "",
        email: "",
        password: "",
        is_admin: false,
        is_active: true,
        rocket_chat_user_id: "none",
      });
    }
  }, [user, form]);
  
  // Handle form submission
  const onSubmit = (data: FormValues) => {
    try {
      setFormError(null);
     
      
      // Validate
      if (!user && !data.password) {
        setFormError("Password is required for new users");
        return;
      }
      
      // Prepare the data
      const userData: UserSaveData = {
        ...data,
        id: user?.id, // Include ID if editing existing user
        rocket_chat_user_id: data.is_admin ? undefined : (data.rocket_chat_user_id === "none" || !data.rocket_chat_user_id ? undefined : parseInt(data.rocket_chat_user_id, 10)),
        permissions: [] // Initialize with empty array
      };
      
      // If editing and password is empty, remove it
      if (user && !userData.password) {
        delete userData.password;
      }
      
      // Add permissions if not admin
      if (!data.is_admin) {
        // Find the actual permission objects from selectedPermissions IDs
        const selectedPermissionObjects: Permission[] = [];
        
        if (permissions && permissions.length > 0) {
          // Loop through all available permissions to find the selected ones
          permissions.forEach(category => {
            category.permissions.forEach(permission => {
              // If this permission's ID is in the selectedPermissions array, add it
              if (selectedPermissions.includes(permission.id)) {
                selectedPermissionObjects.push(permission);
              }
            });
          });
        }
        
        userData.permissions = selectedPermissionObjects;
      } else {
        // For admin users, don't send permissions as they're implied
        userData.permissions = [];
      }
      
      
      onSave(userData);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "An error occurred";
      setFormError(errorMessage);
    }
  };

  return (
    <div className="space-y-6">
      <div>
        <h2 className="text-2xl font-bold mb-2">{user ? "Edit User" : "Add New User"}</h2>
      </div>
      
      {formError && (
        <Alert variant="destructive">
          <AlertDescription>{formError}</AlertDescription>
        </Alert>
      )}
      
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          {/* Basic Information Section */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <FormField
              control={form.control}
              name="username"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Username</FormLabel>
                  <FormControl>
                    <Input {...field} autoComplete="off" />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          
            <FormField
              control={form.control}
              name="password"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{user ? "New Password" : "Password"}</FormLabel>
                  <FormControl>
                    <Input
                      type="password"
                      autoComplete="new-password"
                      {...field}
                      placeholder={user ? "Leave blank to keep current password" : ""}
                    />
                  </FormControl>
               
                    <FormMessage />
                  </FormItem>
                )}
              />
              
              <FormField
                control={form.control}
                name="rocket_chat_user_id"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Rocket Chat User</FormLabel>
                    <FormControl>
                      {form.watch("is_admin") ? (
                        <div className="flex items-center gap-2 p-2 border text-sm rounded-md bg-muted">
                          <span className="text-muted-foreground">
                            Admin users have access to all chat rooms by default
                          </span>
                        </div>
                      ) : (
                        <Select value={field.value || "none"} onValueChange={field.onChange}>
                          <SelectTrigger>
                            <SelectValue placeholder={loadingRocketChatUsers ? "Loading..." : "Select Rocket Chat user..."} />
                          </SelectTrigger>
                          <SelectContent>
                            {!loadingRocketChatUsers && (
                              <SelectItem value="none">
                                <span className="text-muted-foreground">None</span>
                              </SelectItem>
                            )}
                            {rocketChatUsers.map((rcUser) => (
                              <SelectItem key={rcUser.id} value={rcUser.id.toString()}>
                                <div className="flex items-center gap-2">
                                  <Avatar className="h-6 w-6">
                                    <AvatarImage 
                                      src={rcUser.mongo_id ? `${config.chatUrl}/avatar/${rcUser.mongo_id}` : undefined}
                                      alt={rcUser.name || rcUser.username}
                                    />
                                    <AvatarFallback className="text-xs">
                                      {(rcUser.name || rcUser.username).charAt(0).toUpperCase()}
                                    </AvatarFallback>
                                  </Avatar>
                                  <span className={rcUser.active ? '' : 'text-muted-foreground'}>
                                    {rcUser.name || rcUser.username}
                                    {!rcUser.active && <span className="text-xs ml-1">(inactive)</span>}
                                  </span>
                                </div>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      )}
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          
          {/* Status Switches - Two Columns */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <FormField
              control={form.control}
              name="is_admin"
              render={({ field }) => (
                <FormItem className="flex flex-row items-center justify-between p-4 border rounded-md">
                  <div>
                    <FormLabel>Administrator</FormLabel>
                    <FormDescription>
                      Administrators have access to all permissions
                    </FormDescription>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
            
            <FormField
              control={form.control}
              name="is_active"
              render={({ field }) => (
                <FormItem className="flex flex-row items-center justify-between p-4 border rounded-md">
                  <div>
                    <FormLabel>Active</FormLabel>
                    <FormDescription>
                      Inactive users cannot log in
                    </FormDescription>
                  </div>
                  <FormControl>
                    <Switch
                      checked={field.value}
                      onCheckedChange={field.onChange}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
          </div>

                      {/* Permissions Section */}
            {permissions && permissions.length > 0 && (
              <>
                <PermissionSelector
                  permissionsByCategory={permissions}
                  selectedPermissions={form.watch("is_admin") ? getAllPermissionIds(permissions) : selectedPermissions}
                  onChange={setSelectedPermissions}
                  disabled={form.watch("is_admin")}
                  isAdmin={form.watch("is_admin")}
                />
                {!form.watch("is_admin") && selectedPermissions.length === 0 && (
                  <Alert variant="destructive">
                    <AlertDescription>
                      Warning: This user has no permissions selected. They won't be able to access anything.
                    </AlertDescription>
                  </Alert>
                )}
              </>
            )}
          
          <div className="flex justify-end space-x-4">
            <Button type="button" variant="outline" onClick={onCancel}>
              Cancel
            </Button>
            <Button type="submit">
              {user ? "Update User" : "Create User"}
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
} 
