"use client";

import { useWatch } from "react-hook-form";
import { AlertCircle, LockKeyhole, Network, Plus, Save, Trash2 } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { FieldGroup } from "@/components/ui/field";
import { Spinner } from "@/components/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { FormErrorAlert, SwitchField, TextField } from "@/components/app/form-fields";
import { FactList, SectionCard } from "@/components/app/page";
import { cn } from "@/lib/utils";
import { useAuth } from "../../auth/auth-context";
import { ErrorState, UnauthorizedState } from "../../components/ui/page-states";
import StatusBadge from "../../components/ui/status-badge";
import { EditorSkeleton } from "../roles/roles-ui";
import { SettingsFrame, SettingsShell, UnsavedHint } from "../settings-layout";
import { useDepartmentForm, useDepartmentManagement } from "./useDepartmentManagement";

export function DepartmentsPage() {
  return <SettingsShell title="Departments"><DepartmentsWorkspace /></SettingsShell>;
}

function DepartmentsWorkspace() {
  const { can, organization } = useAuth();
  const canView = can("users.view") || can("users.create") || can("organization.manage");
  const canManage = can("organization.manage");
  const departments = useDepartmentManagement(canView);
  const description = `${organization?.name || "Your organization"} can use locked system departments or create custom departments for its own team structure.`;

  if (!canView) {
    return <SettingsFrame title="Departments" description={description}>
      <Card className="py-0"><UnauthorizedState title="Departments are not available for your account" permission="users.view" backHref="/settings" backLabel="Back to settings" /></Card>
    </SettingsFrame>;
  }

  const failedEmpty = departments.error && !departments.departments.length;
  const actions = canManage && !departments.isLoading && !failedEmpty
    ? <Button size="sm" onClick={() => departments.select(null)}><Plus /> New department</Button>
    : null;

  return <SettingsFrame title="Departments" description={description} actions={actions}>
    {departments.isLoading && <EditorSkeleton />}
    {!departments.isLoading && failedEmpty && <Card className="py-0"><ErrorState error={departments.error} title="Departments could not be loaded" onRetry={departments.retry} /></Card>}
    {!departments.isLoading && departments.error && !failedEmpty && <Alert variant="destructive">
      <AlertCircle />
      <AlertDescription className="flex flex-wrap items-center gap-x-3 gap-y-2"><span>The department list could not be refreshed: {departments.error.message}</span><Button variant="outline" size="sm" onClick={departments.refresh}>Try again</Button></AlertDescription>
    </Alert>}

    {!departments.isLoading && !failedEmpty && <div className={cn("grid gap-6 xl:grid-cols-[300px_minmax(0,1fr)] xl:items-start", departments.isRefreshing && "opacity-80")} aria-busy={departments.isRefreshing}>
      <DepartmentLibrary departments={departments} canManage={canManage} />
      <DepartmentEditor departments={departments} canManage={canManage} />
    </div>}
  </SettingsFrame>;
}

function DepartmentLibrary({ departments, canManage }) {
  return <SectionCard
    title="Department library"
    icon={Network}
    actions={departments.isRefreshing ? <Spinner className="text-muted-foreground" /> : <Badge variant="outline">{departments.customDepartments.length} custom</Badge>}
    className="xl:sticky xl:top-20"
    contentClassName="grid gap-5"
  >
    <DepartmentList title="Custom departments" empty="No custom departments yet." departments={departments.customDepartments} selected={departments.selected} onSelect={departments.select} onDelete={departments.deleteDepartment} deletingId={departments.deletingId} canDelete={canManage} />
    <DepartmentList title="System defaults" empty="No system departments found." departments={departments.systemDepartments} selected={departments.selected} onSelect={departments.select} locked />
  </SectionCard>;
}

function DepartmentList({ title, empty, departments, selected, onSelect, onDelete, deletingId, canDelete = false, locked = false }) {
  return <div className="grid gap-1.5">
    <h3 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{title}</h3>
    {departments.length ? <ul className="grid gap-1">{departments.map((department) => {
      const active = selected?.id === department.id;
      return <li key={department.id} className={cn("flex items-center gap-1 rounded-md transition-colors", active ? "bg-muted" : "hover:bg-muted/60")}>
        <button type="button" onClick={() => onSelect(department)} aria-current={active ? "true" : undefined} className="grid min-w-0 flex-1 gap-0.5 rounded-md px-3 py-2 text-left focus-visible:outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50">
          <span className={cn("truncate text-sm", active && "font-medium", !department.is_active && "text-muted-foreground")}>{department.name}</span>
          <span className="flex items-center gap-1 text-xs text-muted-foreground">
            {department.users_count || 0} users · {department.is_active ? "active" : "inactive"}{locked && <><span aria-hidden="true">·</span><LockKeyhole className="size-3" /> locked</>}
          </span>
        </button>
        {canDelete && !department.is_system && <Tooltip>
          <TooltipTrigger asChild>
            <Button variant="ghost" size="icon-sm" className="mr-1 text-muted-foreground hover:text-destructive" aria-label={`Delete department ${department.name}`} disabled={deletingId === department.id} onClick={() => onDelete(department)}>
              {deletingId === department.id ? <Spinner /> : <Trash2 />}
            </Button>
          </TooltipTrigger>
          <TooltipContent>Delete {department.name}</TooltipContent>
        </Tooltip>}
      </li>;
    })}</ul> : <p className="px-3 text-sm text-muted-foreground">{empty}</p>}
  </div>;
}

function DepartmentEditor({ departments, canManage }) {
  const selected = departments.selected;
  const editor = useDepartmentForm({
    department: selected?.is_system ? null : selected,
    onSaved: departments.handleSaved,
    onDirtyChange: departments.setEditorDirty,
  });
  const isActive = useWatch({ control: editor.form.control, name: "is_active" });
  const { isDirty, isSubmitting } = editor.form.formState;

  if (selected?.is_system) {
    return <SectionCard title={selected.name} icon={LockKeyhole} actions={<Badge variant="outline">System default</Badge>} description="System departments keep onboarding simple and cannot be edited. Create a custom department when this workspace needs a different team name.">
      <FactList columns={2} items={[
        ["Key", <code key="key" className="font-mono text-xs">{selected.key}</code>],
        ["Status", <StatusBadge key="status" status={selected.is_active ? "active" : "inactive"} tone={selected.is_active ? "success" : "neutral"} />],
        ["Assigned users", selected.users_count || 0],
        ["Description", selected.description || "No description"],
      ]} />
    </SectionCard>;
  }

  if (!canManage) {
    return <Card className="py-0"><UnauthorizedState compact title="You can view departments only" permission="organization.manage" /></Card>;
  }

  return <form onSubmit={editor.submit} noValidate>
    <SectionCard
      title={selected ? `Edit ${selected.name}` : "New department"}
      icon={Network}
      description={selected ? `${selected.users_count || 0} team member${selected.users_count === 1 ? " is" : "s are"} in this department.` : "Add a department your buying house uses, then assign members to it from the team page."}
      actions={<StatusBadge status={isActive ? "active" : "inactive"} tone={isActive ? "success" : "neutral"} />}
      contentClassName="grid gap-5"
    >
      <FormErrorAlert form={editor.form} />
      <FieldGroup className="grid gap-5 md:grid-cols-2">
        <TextField control={editor.form.control} name="name" label="Department name" description="Example: Compliance, Sourcing, Documentation." />
        <TextField control={editor.form.control} name="description" label="Description" description="Short note shown to admins." />
        <SwitchField control={editor.form.control} name="is_active" label="Active" description="Active departments can be assigned to users." className="md:col-span-2" />
      </FieldGroup>
      <div className="flex flex-wrap items-center justify-end gap-3 border-t pt-4">
        <UnsavedHint show={isDirty} />
        {isDirty && <Button type="button" variant="outline" disabled={isSubmitting} onClick={editor.discard}>Discard</Button>}
        <Button type="submit" disabled={isSubmitting || (selected && !isDirty)}>{isSubmitting ? <Spinner /> : <Save />} Save department</Button>
      </div>
    </SectionCard>
  </form>;
}
