import { useEffect, useState } from "react";
import { isAxiosError } from "axios";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@edr/ui-common";

import { api } from "@/auth/http";
import { useAuth } from "@/auth/useAuth";

interface LocaleText {
  en?: string;
  am?: string;
}

interface EmployeeUserRecord {
  id: string;
  name?: LocaleText;
  email?: string;
  phoneNumber?: string;
  username?: string;
}

interface EmployeePositionSummary {
  id: string;
  position?: {
    id: string;
    name?: LocaleText;
    key?: string;
  };
}

interface EmployeeRecord {
  id: string;
  name?: LocaleText;
  status?: string;
  user?: EmployeeUserRecord;
  employeePositions?: EmployeePositionSummary[];
}

interface ListResponse<T> {
  count?: number;
  items?: T[];
  data?: T[];
}

const getLocaleLabel = (value?: LocaleText | null, fallback = "Unnamed") =>
  value?.en ?? value?.am ?? fallback;

const getItems = <T,>(payload: ListResponse<T> | T[] | undefined | null) => {
  if (!payload) {
    return [] as T[];
  }

  if (Array.isArray(payload)) {
    return payload;
  }

  return payload.items ?? payload.data ?? [];
};

const getEmployeeDisplayName = (employee: EmployeeRecord) =>
  getLocaleLabel(
    employee.name ?? employee.user?.name,
    employee.user?.email ?? employee.user?.username ?? employee.id,
  );

const EmployeesPage = () => {
  const { user } = useAuth();
  const [employees, setEmployees] = useState<EmployeeRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [selectedEmployee, setSelectedEmployee] = useState<EmployeeRecord | null>(null);

  useEffect(() => {
    let isMounted = true;
    const organizationIds = Array.from(
      new Set(
        (user?.employee ?? [])
          .map((employee) => employee.organizationId)
          .filter((organizationId): organizationId is string => Boolean(organizationId)),
      ),
    );

    const loadEmployees = async () => {
      setLoading(true);
      setErrorMessage(null);

      if (!organizationIds.length) {
        setEmployees([]);
        setErrorMessage("No employee organization scope is available for this account.");
        setLoading(false);
        return;
      }

      try {
        const responses = await Promise.all(
          organizationIds.map((organizationId) =>
            api.get<ListResponse<EmployeeRecord>>(
              `/backoffice/organizations/${organizationId}/employees`,
              {
                params: {
                  skip: 0,
                  take: 1000,
                },
              },
            ),
          ),
        );

        if (!isMounted) {
          return;
        }

        const uniqueEmployees = Array.from(
          new Map(
            responses
              .flatMap((response) => getItems(response.data))
              .map((employee) => [employee.id, employee]),
          ).values(),
        );

        setEmployees(
          uniqueEmployees.sort((left, right) =>
            getEmployeeDisplayName(left).localeCompare(getEmployeeDisplayName(right)),
          ),
        );
      } catch (error) {
        if (!isMounted) {
          return;
        }

        setErrorMessage(
          isAxiosError(error)
            ? error.response?.data?.message ?? "Unable to load employees."
            : "Unable to load employees.",
        );
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    void loadEmployees();

    return () => {
      isMounted = false;
    };
  }, [user]);

  return (
    <section className="p-6">
      <div className="space-y-6 rounded-2xl border border-border bg-card p-8 shadow-sm">
        <div className="space-y-3">
          <p className="text-sm font-medium uppercase tracking-[0.2em] text-muted-foreground">
            User Management
          </p>
          <div className="flex items-start justify-between gap-4">
            <div>
              <h1 className="text-3xl font-semibold text-foreground">Employees</h1>
              <p className="mt-3 max-w-2xl text-sm text-muted-foreground">
                Browse employees within your accessible scope and open a record to review contact and position details.
              </p>
            </div>
            <div className="rounded-full border border-border bg-muted px-3 py-1 text-sm font-medium text-muted-foreground">
              {employees.length} employees
            </div>
          </div>
        </div>

        {loading ? (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            Loading employees...
          </div>
        ) : errorMessage ? (
          <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-8 text-center text-sm text-red-700 dark:border-red-950 dark:bg-red-950/30 dark:text-red-300">
            {errorMessage}
          </div>
        ) : employees.length ? (
          <div className="overflow-x-auto rounded-2xl border border-border">
            <table className="min-w-[980px] w-full border-collapse text-left text-sm">
              <thead className="bg-muted/60 text-muted-foreground">
                <tr>
                  <th className="px-4 py-3 font-medium">Name</th>
                  <th className="px-4 py-3 font-medium">Username</th>
                  <th className="px-4 py-3 font-medium">Email</th>
                  <th className="px-4 py-3 font-medium">Phone</th>
                  <th className="px-4 py-3 font-medium">Status</th>
                  <th className="px-4 py-3 font-medium">Positions</th>
                </tr>
              </thead>
              <tbody>
                {employees.map((employee) => {
                  const positions = employee.employeePositions?.map((item) => getLocaleLabel(item.position?.name, item.position?.key ?? "Unnamed")) ?? [];

                  return (
                    <tr
                      key={employee.id}
                      onClick={() => setSelectedEmployee(employee)}
                      className="cursor-pointer border-t border-border bg-background transition hover:bg-accent/20"
                    >
                      <td className="px-4 py-3 font-medium text-foreground">{getEmployeeDisplayName(employee)}</td>
                      <td className="px-4 py-3 text-muted-foreground">{employee.user?.username ?? "-"}</td>
                      <td className="px-4 py-3 text-muted-foreground">{employee.user?.email ?? "-"}</td>
                      <td className="px-4 py-3 text-muted-foreground">{employee.user?.phoneNumber ?? "-"}</td>
                      <td className="px-4 py-3 text-muted-foreground">{employee.status ?? "-"}</td>
                      <td className="px-4 py-3 text-muted-foreground">{positions.join(", ") || "-"}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
            No employees are available in your scope.
          </div>
        )}
      </div>

      <Dialog open={Boolean(selectedEmployee)} onOpenChange={(open) => !open && setSelectedEmployee(null)}>
        <DialogContent className="max-h-[85vh] overflow-y-auto sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>
              {selectedEmployee ? getEmployeeDisplayName(selectedEmployee) : "Employee details"}
            </DialogTitle>
            <DialogDescription>
              {selectedEmployee
                ? "Review the employee profile, contact information, and assigned positions."
                : undefined}
            </DialogDescription>
          </DialogHeader>

          {selectedEmployee ? (
            <div className="space-y-6">
              <div className="grid gap-4 rounded-2xl border border-border bg-muted/40 p-4 sm:grid-cols-2">
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Employee name
                  </p>
                  <p className="mt-2 text-sm font-semibold text-foreground">
                    {getEmployeeDisplayName(selectedEmployee)}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Status
                  </p>
                  <p className="mt-2 text-sm font-semibold text-foreground">
                    {selectedEmployee.status ?? "-"}
                  </p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Username
                  </p>
                  <p className="mt-2 text-sm text-foreground">{selectedEmployee.user?.username ?? "-"}</p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Email
                  </p>
                  <p className="mt-2 text-sm text-foreground">{selectedEmployee.user?.email ?? "-"}</p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Phone
                  </p>
                  <p className="mt-2 text-sm text-foreground">{selectedEmployee.user?.phoneNumber ?? "-"}</p>
                </div>
                <div>
                  <p className="text-xs font-medium uppercase tracking-[0.18em] text-muted-foreground">
                    Employee ID
                  </p>
                  <p className="mt-2 font-mono text-sm text-foreground">{selectedEmployee.id}</p>
                </div>
              </div>

              <div className="space-y-3">
                <div className="flex items-center justify-between gap-3">
                  <h2 className="text-sm font-semibold text-foreground">Assigned positions</h2>
                  <div className="rounded-full border border-border bg-muted px-3 py-1 text-xs font-medium text-muted-foreground">
                    {selectedEmployee.employeePositions?.length ?? 0} positions
                  </div>
                </div>

                {selectedEmployee.employeePositions?.length ? (
                  <div className="grid gap-3 md:grid-cols-2">
                    {selectedEmployee.employeePositions.map((item) => (
                      <article
                        key={item.id}
                        className="rounded-2xl border border-border/70 bg-background/80 p-4 shadow-sm"
                      >
                        <p className="truncate text-sm font-semibold text-foreground">
                          {getLocaleLabel(item.position?.name, item.position?.key ?? "Unnamed")}
                        </p>
                        <p className="mt-1 truncate font-mono text-xs text-muted-foreground/90">
                          {item.position?.key ?? "-"}
                        </p>
                      </article>
                    ))}
                  </div>
                ) : (
                  <div className="rounded-2xl border border-dashed border-border bg-muted px-4 py-8 text-center text-sm text-muted-foreground">
                    No positions are assigned to this employee.
                  </div>
                )}
              </div>
            </div>
          ) : null}
        </DialogContent>
      </Dialog>
    </section>
  );
};

export default EmployeesPage;
