"use client";

import { useState, useEffect, useMemo } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { DatePicker } from "@/components/ui/date-picker";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { CreateUserData } from "@/lib/types";
import { api } from "@/lib/store/api";
import { apiCall } from "@/lib/store/api-call";
import {
  BACKEND_ROLES,
  EMPLOYMENT_TYPES,
  TECH_STACK_OPTIONS,
  DESIGN_SUB_TEAM_OPTIONS,
  isDesignHead,
} from "@/lib/constants";
import { ArrowLeft, Save, User, AlertCircle } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { AppSpinner } from "@/components/ui/app-loader";

function getAllowedCreateRoles(userRole?: string | null): string[] {
  switch (userRole) {
    case "SUPER_ADMIN":
      return [
        "SUPER_ADMIN",
        "UPPER_MANAGEMENT",
        "MANAGER",
        "UNIT_LEAD",
        "MEMBER",
      ];
    case "UPPER_MANAGEMENT":
      return [];
    case "MANAGER":
      return ["UNIT_LEAD", "MEMBER"];
    case "UNIT_LEAD":
      return ["MEMBER"];
    default:
      return [];
  }
}

export function UserForm() {
  const router = useRouter();
  const { data: session, status } = useSession();
  const [formData, setFormData] = useState<CreateUserData>({
    employeeId: "",
    name: "",
    email: "",
    password: "",
    designation: "",
    team: "",
    role: "MEMBER",
    personalPhone: "",
    employmentType: "Full-time",
    joiningDate: new Date(),
    managerId: "auto-assign",
    salary: undefined,
    techStack: undefined,
    designSubTeam: undefined,
  });

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [departmentsLoading, setDepartmentsLoading] = useState(true);
  const [manageableTeams, setManageableTeams] = useState<string[]>([]);
  const [allDepartments, setAllDepartments] = useState<
    Array<{ id: string; name: string }>
  >([]);
  const [availableDesignations, setAvailableDesignations] = useState<string[]>(
    [],
  );
  const [availableManagers, setAvailableManagers] = useState<
    Array<{ id: string; name: string; role: string }>
  >([]);

  // Derive synchronously so soft navigation never flashes "no permission" before useEffect
  const allowedRoles = useMemo(
    () => getAllowedCreateRoles(session?.user?.role),
    [session?.user?.role],
  );

  // Fetch departments once session is ready (API scopes by role)
  useEffect(() => {
    if (status !== "authenticated" || !session?.user?.role) {
      if (status !== "loading") setDepartmentsLoading(false);
      return;
    }

    let cancelled = false;
    setDepartmentsLoading(true);

    apiCall<Array<{ id: string; name: string }>>(
      api.endpoints.getDepartments.initiate(),
    )
      .then((depts: Array<{ id: string; name: string }>) => {
        if (cancelled) return;
        setAllDepartments(depts);
        const manageable = depts.map((d) => d.name);
        setManageableTeams(manageable);
        if (manageable.length === 1) {
          setFormData((prev) => ({ ...prev, team: manageable[0] }));
        }
      })
      .catch(() => {
        if (!cancelled) setAllDepartments([]);
      })
      .finally(() => {
        if (!cancelled) setDepartmentsLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [status, session?.user?.role, session?.user?.department]);

  // Fetch designations dynamically when department changes
  useEffect(() => {
    if (!formData.team) {
      setAvailableDesignations([]);
      setAvailableManagers([]);
      setFormData((prev) => ({
        ...prev,
        designation: "",
        managerId: "auto-assign",
      }));
      return;
    }
    const dept = allDepartments.find((d) => d.name === formData.team);
    if (!dept) return;

    apiCall<Array<{ id: string; title: string }>>(
      api.endpoints.getDesignations.initiate({ departmentId: dept.id }),
    )
      .then((data: Array<{ id: string; title: string }>) => {
        // Deduplicate titles (legacy duplicate rows may still exist until cleaned up)
        const titles = Array.from(new Set(data.map((d) => d.title)));
        setAvailableDesignations(titles);
        // Clear designation if it no longer belongs to the new department
        setFormData((prev) => ({
          ...prev,
          designation: titles.includes(prev.designation)
            ? prev.designation
            : "",
        }));
      })
      .catch(() => setAvailableDesignations([]));

    fetchAvailableManagers(formData.team);
  }, [formData.team, allDepartments]);

  const fetchAvailableManagers = async (team: string) => {
    try {
      const data = await apiCall<any>(
        api.endpoints.getUsers.initiate({
          department: team,
          role: "MANAGER,UNIT_LEAD",
          limit: 100,
          isActive: true,
        }),
      );
      if (data?.users) {
        const managers = data.users
          .filter(
            (user: any) =>
              user.isActive !== false &&
              ["MANAGER", "UNIT_LEAD"].includes(user.role),
          )
          .map((user: any) => ({
            id: user.id,
            name: user.name,
            role: user.role,
          }));
        setAvailableManagers(managers);
      }
    } catch (error) {
      console.error("Error fetching managers:", error);
      setAvailableManagers([]);
    }
  };

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

    try {
      // Create username from email
      const username = formData.email.split("@")[0];

      // Prepare user data for API
      const userData = {
        employeeId: formData.employeeId,
        name: formData.name,
        username: username,
        email: formData.email,
        password: formData.password,
        role: formData.role,
        position: formData.designation,
        department: formData.team,
        phone: formData.personalPhone,
        joinDate: formData.joiningDate,
        managerId:
          formData.managerId === "auto-assign" ? undefined : formData.managerId,
        // Add employment type and other optional fields
        employmentType: formData.employmentType,
        salary: formData.salary,
        techStack: formData.techStack,
        designSubTeam: formData.designSubTeam,
      };

      // Debug logging
      console.log(
        "🔍 Frontend - Creating user with data:",
        JSON.stringify(userData, null, 2),
      );
      console.log("🔍 Frontend - designSubTeam value:", formData.designSubTeam);

      console.log("Submitting user data:", userData);

      try {
        const result = await apiCall(
          api.endpoints.createAdminUser.initiate(userData),
        );
        console.log("User created successfully:", result);
      } catch (err: any) {
        const errorData = err?.data;
        if (errorData?.details && Array.isArray(errorData.details)) {
          const validationErrors = errorData.details
            .map((detail: any) => `${detail.path.join(".")}: ${detail.message}`)
            .join("\n");
          throw new Error(`Validation failed:\n${validationErrors}`);
        }
        throw new Error(
          errorData?.error || err?.message || "Failed to create user",
        );
      }

      // Redirect to users list
      router.push("/dashboard/users");
    } catch (error) {
      console.error("Error creating user:", error);
      alert("Failed to create user: " + (error as Error).message);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleInputChange = (
    field: keyof CreateUserData,
    value: string | Date | number | undefined,
  ) => {
    // Special handling for date fields to ensure they're valid
    if (field === "joiningDate" && value instanceof Date) {
      // Only update if the date is valid
      if (isNaN(value.getTime())) {
        console.warn("Invalid date provided for joiningDate, ignoring");
        return;
      }
    }

    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const canCreateUsers = allowedRoles.length > 0;

  if (
    status === "loading" ||
    (status === "authenticated" && departmentsLoading && canCreateUsers)
  ) {
    return (
      <div className="max-w-2xl mx-auto flex min-h-[40vh] flex-col items-center justify-center gap-3">
        <AppSpinner className="h-6 w-6 text-primary" />
        <p className="text-sm text-muted-foreground">
          Loading create user form…
        </p>
      </div>
    );
  }

  if (status === "unauthenticated") {
    return (
      <div className="max-w-2xl mx-auto">
        <Alert>
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>Please sign in to create users.</AlertDescription>
        </Alert>
      </div>
    );
  }

  if (!canCreateUsers) {
    return (
      <div className="max-w-2xl mx-auto">
        <div className="mb-8">
          <Button
            variant="ghost"
            onClick={() => router.back()}
            className="mb-4"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back
          </Button>
        </div>
        <Alert>
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            You don&apos;t have permission to create users. Please contact your
            administrator.
          </AlertDescription>
        </Alert>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-2xl pb-2">
      <div className="mb-6">
        <Button variant="ghost" onClick={() => router.back()} className="mb-3 h-9 px-2">
          <ArrowLeft className="h-4 w-4 mr-2" />
          Back
        </Button>
        <div className="flex items-center space-x-3">
          <div className="p-2 bg-primary/10 rounded-lg">
            <User className="h-6 w-6 text-primary" />
          </div>
          <div>
            <h1 className="text-3xl font-bold text-foreground">
              Create New User
            </h1>
            <p className="text-muted-foreground">
              {manageableTeams.length === 1
                ? `Add a new member to the ${manageableTeams[0]} department`
                : "Add a new member to your organization"}
            </p>
          </div>
        </div>
      </div>

      <div className="rounded-xl border border-border bg-card p-6 sm:p-8 text-card-foreground shadow-none">
        <form onSubmit={handleSubmit} className="space-y-8">
          {/* Basic Information */}
          <div className="space-y-6">
            <div className="border-b border-border pb-4">
              <h3 className="text-lg font-semibold text-foreground">
                Basic Information
              </h3>
              <p className="text-sm text-muted-foreground">
                Essential details for user account creation
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="employeeId">Employee ID *</Label>
                <Input
                  id="employeeId"
                  type="text"
                  value={formData.employeeId}
                  onChange={(e) =>
                    handleInputChange("employeeId", e.target.value)
                  }
                  placeholder="Enter employee ID (e.g., EMP001)"
                  required
                  className="h-11"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="name">Full Name *</Label>
                <Input
                  id="name"
                  type="text"
                  value={formData.name}
                  onChange={(e) => handleInputChange("name", e.target.value)}
                  placeholder="Enter full name"
                  required
                  className="h-11"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="email">Work Email Address *</Label>
                <Input
                  id="email"
                  type="email"
                  value={formData.email}
                  onChange={(e) => handleInputChange("email", e.target.value)}
                  placeholder="Enter work email address"
                  required
                  className="h-11"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="password">Password *</Label>
              <Input
                id="password"
                type="password"
                value={formData.password}
                onChange={(e) => handleInputChange("password", e.target.value)}
                placeholder="Enter password (minimum 8 characters)"
                required
                minLength={8}
                className="h-11"
              />
              <p className="text-sm text-muted-foreground">
                Password must be at least 8 characters long
              </p>
            </div>
          </div>

          {/* Department & Role Assignment */}
          <div className="space-y-6">
            <div className="border-b border-border pb-4">
              <h3 className="text-lg font-semibold text-foreground">
                Department & Role Assignment
              </h3>
              <p className="text-sm text-muted-foreground">
                Select a department first, then choose the appropriate
                designation
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="team">Department *</Label>
                {manageableTeams.length === 1 ? (
                  <div className="h-11 px-3 flex items-center rounded-md border border-input bg-muted text-sm font-medium">
                    {manageableTeams[0]}
                  </div>
                ) : (
                  <Select
                    value={formData.team}
                    onValueChange={(value) => handleInputChange("team", value)}
                    required
                  >
                    <SelectTrigger className="h-11">
                      <SelectValue placeholder="Select department" />
                    </SelectTrigger>
                    <SelectContent>
                      {manageableTeams.map((dept) => (
                        <SelectItem key={dept} value={dept}>
                          {dept}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="designation">Designation *</Label>
                <Select
                  value={formData.designation}
                  onValueChange={(value) =>
                    handleInputChange("designation", value)
                  }
                  required
                  disabled={!formData.team}
                >
                  <SelectTrigger className="h-11">
                    <SelectValue
                      placeholder={
                        formData.team
                          ? "Select designation"
                          : "Select department first"
                      }
                    />
                  </SelectTrigger>
                  <SelectContent>
                    {availableDesignations.map((designation) => (
                      <SelectItem key={designation} value={designation}>
                        {designation}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                {formData.team && availableDesignations.length === 0 && (
                  <p className="text-sm text-amber-600 text-xs">
                    No designations found for {formData.team}. Add them in
                    Designation Management.
                  </p>
                )}
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="role">System Role *</Label>
              <Select
                value={formData.role}
                onValueChange={(value: string) =>
                  handleInputChange("role", value)
                }
                required
              >
                <SelectTrigger className="h-11">
                  <SelectValue placeholder="Select role" />
                </SelectTrigger>
                <SelectContent>
                  {allowedRoles.map((role) => (
                    <SelectItem key={role} value={role}>
                      {BACKEND_ROLES[role as keyof typeof BACKEND_ROLES]}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-sm text-muted-foreground">
                System role determines access permissions and capabilities
              </p>
            </div>

            {/* Manager Assignment */}
            <div className="space-y-2">
              <Label htmlFor="manager">Reports To (Manager)</Label>
              <Select
                value={formData.managerId || "auto-assign"}
                onValueChange={(value) => handleInputChange("managerId", value)}
                disabled={!formData.team || availableManagers.length === 0}
              >
                <SelectTrigger className="h-11">
                  <SelectValue
                    placeholder={
                      !formData.team
                        ? "Select department first"
                        : availableManagers.length === 0
                          ? "No managers available"
                          : "Select manager (optional)"
                    }
                  />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="auto-assign">
                    Auto-assign based on hierarchy
                  </SelectItem>
                  {availableManagers.map((manager) => (
                    <SelectItem key={manager.id} value={manager.id}>
                      {manager.name} ({manager.role})
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-sm text-muted-foreground">
                {!formData.managerId || formData.managerId === "auto-assign"
                  ? "If not specified, will be auto-assigned to appropriate manager in the team"
                  : "This user will report to the selected manager"}
              </p>
            </div>
          </div>

          {/* Optional Information */}
          <div className="space-y-6">
            <div className="border-b border-border pb-4">
              <h3 className="text-lg font-semibold text-foreground">
                Additional Information
              </h3>
              <p className="text-sm text-muted-foreground">
                Optional fields that can be updated later in profile
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <div className="space-y-2">
                <Label htmlFor="personalPhone">Personal Phone</Label>
                <Input
                  id="personalPhone"
                  type="tel"
                  value={formData.personalPhone || ""}
                  onChange={(e) =>
                    handleInputChange("personalPhone", e.target.value)
                  }
                  placeholder="Enter personal phone number"
                  className="h-11"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="employmentType">Employment Type</Label>
                <Select
                  value={formData.employmentType || "Full-time"}
                  onValueChange={(value) =>
                    handleInputChange("employmentType", value)
                  }
                >
                  <SelectTrigger className="h-11">
                    <SelectValue placeholder="Select type" />
                  </SelectTrigger>
                  <SelectContent>
                    {EMPLOYMENT_TYPES.map((type) => (
                      <SelectItem key={type} value={type}>
                        {type}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Tech Stack field - only show for Production department */}
              {formData.team === "Production" && (
                <div className="space-y-2">
                  <Label htmlFor="techStack">Tech Stack *</Label>
                  <Select
                    value={formData.techStack || ""}
                    onValueChange={(value) =>
                      handleInputChange("techStack", value)
                    }
                    required
                  >
                    <SelectTrigger className="h-11">
                      <SelectValue placeholder="Select tech stack" />
                    </SelectTrigger>
                    <SelectContent>
                      {TECH_STACK_OPTIONS.map((stack) => (
                        <SelectItem key={stack} value={stack}>
                          {stack}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-sm text-muted-foreground">
                    Required for Production department members
                  </p>
                </div>
              )}

              {/* Design Sub-Team field - only show for Design department */}
              {formData.team === "Design" && (
                <div className="space-y-2">
                  <Label htmlFor="designSubTeam">
                    Design Sub-Team {!isDesignHead(formData.designation) && "*"}
                  </Label>
                  <Select
                    value={formData.designSubTeam || ""}
                    onValueChange={(value) =>
                      handleInputChange("designSubTeam", value)
                    }
                    required={!isDesignHead(formData.designation)}
                  >
                    <SelectTrigger className="h-11">
                      <SelectValue placeholder="Select design sub-team" />
                    </SelectTrigger>
                    <SelectContent>
                      {DESIGN_SUB_TEAM_OPTIONS.map((subTeam) => (
                        <SelectItem key={subTeam} value={subTeam}>
                          {subTeam}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-sm text-muted-foreground">
                    {isDesignHead(formData.designation)
                      ? "Optional for design department heads"
                      : "Required for design team members"}
                  </p>
                </div>
              )}

              <div className="space-y-2">
                <Label htmlFor="salary">Monthly Salary (PKR)</Label>
                <Input
                  id="salary"
                  type="number"
                  min="0"
                  step="5000"
                  value={formData.salary || ""}
                  onChange={(e) =>
                    handleInputChange(
                      "salary",
                      e.target.value
                        ? (parseInt(e.target.value) as any)
                        : (undefined as any),
                    )
                  }
                  placeholder="Enter monthly salary"
                  className="h-11"
                />
                <p className="text-sm text-muted-foreground">
                  Optional - monthly salary in PKR
                </p>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="joiningDate">Employee Joining Date</Label>
              <DatePicker
                id="joiningDate"
                value={
                  formData.joiningDate && !isNaN(formData.joiningDate.getTime())
                    ? formData.joiningDate.toISOString().split("T")[0]
                    : ""
                }
                onChange={(iso) => {
                  if (iso) {
                    const date = new Date(iso);
                    if (!isNaN(date.getTime())) {
                      handleInputChange("joiningDate", date);
                    }
                  } else {
                    handleInputChange("joiningDate", new Date());
                  }
                }}
                clearable
                buttonClassName="h-11"
              />
              <p className="text-sm text-muted-foreground">
                Leave empty to use today&apos;s date
              </p>
            </div>
          </div>

          <div className="flex justify-end space-x-4 pt-6 border-t">
            <Button
              type="button"
              variant="outline"
              onClick={() => router.back()}
              disabled={isSubmitting}
            >
              Cancel
            </Button>
            <Button
              type="submit"
              disabled={isSubmitting}
              className="min-w-[120px]"
            >
              {isSubmitting ? (
                <>
                  <AppSpinner className="mr-2" />
                  Creating...
                </>
              ) : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  Create User
                </>
              )}
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
}
