'use client';

import { useState, useEffect, useCallback } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Label } from '@/components/ui/label';
import { toast } from '@/hooks/use-toast';
import { api } from '@/lib/store/api';
import { apiCall } from '@/lib/store/api-call';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Building2,
  Plus,
  Search,
  Pencil,
  Trash2,
  UserCircle,
  Layers,
  ChevronDown,
  ChevronUp,
} from 'lucide-react';
import { OrgTablePageSkeleton } from '@/components/ui/loading-skeletons';
import { AppSpinner } from '@/components/ui/app-loader';
import { FilterSelect } from '@/components/ui/filter-select';
import { TablePagination } from '@/components/ui/table-pagination';
import { cn } from '@/lib/utils';

interface Manager {
  id: string;
  name: string;
  position: string;
  department: string;
}

interface Department {
  id: string;
  name: string;
  description: string | null;
  managerId: string | null;
  manager: Manager | null;
  createdAt: string;
  updatedAt: string;
  _count: { designations: number };
}

interface FormState {
  name: string;
  description: string;
  managerId: string;
}

const EMPTY_FORM: FormState = { name: '', description: '', managerId: '' };
const PAGE_SIZE = 10;

function isHROrAdmin(role: string, department: string) {
  if (role === 'SUPER_ADMIN' || role === 'UPPER_MANAGEMENT') return true;
  if (role === 'MANAGER' && department === 'HR') return true;
  return false;
}

type SortField = 'name' | 'manager' | 'designations' | 'createdAt';
type SortDir = 'asc' | 'desc';

export default function DepartmentsPage() {
  const { data: session, status } = useSession();
  const router = useRouter();

  const [departments, setDepartments] = useState<Department[]>([]);
  const [managers, setManagers] = useState<Manager[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [sortField, setSortField] = useState<SortField>('name');
  const [sortDir, setSortDir] = useState<SortDir>('asc');
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  const [showModal, setShowModal] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const [saving, setSaving] = useState(false);

  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
  const [deleting, setDeleting] = useState(false);

  const canManage = session ? isHROrAdmin(session.user.role, session.user.department) : false;
  const canView = session
    ? ['SUPER_ADMIN', 'UPPER_MANAGEMENT', 'MANAGER'].includes(session.user.role)
    : false;

  useEffect(() => {
    const t = setTimeout(() => setDebouncedSearch(search.trim()), 300);
    return () => clearTimeout(t);
  }, [search]);

  useEffect(() => {
    setPage(1);
  }, [debouncedSearch, sortField, sortDir]);

  const fetchDepartments = useCallback(async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: String(page),
        limit: String(PAGE_SIZE),
        sort: sortField,
        dir: sortDir,
      });
      if (debouncedSearch) params.set('search', debouncedSearch);

      const data = await apiCall<any>(
        api.endpoints.getDepartments.initiate({
          page,
          limit: PAGE_SIZE,
          sort: sortField,
          dir: sortDir,
          ...(debouncedSearch ? { search: debouncedSearch } : {}),
        }),
      );
      setDepartments(data.departments || []);
      setTotal(data.pagination?.total ?? 0);
    } catch {
      toast({ title: 'Error', description: 'Could not load departments', variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  }, [page, debouncedSearch, sortField, sortDir]);

  const fetchManagers = useCallback(async () => {
    try {
      const data = await apiCall<any>(
        api.endpoints.getAdminUsers.initiate({ limit: 200 }),
      );
      setManagers(
        (data.users || []).filter((u: any) =>
          ['MANAGER', 'UNIT_LEAD', 'UPPER_MANAGEMENT', 'SUPER_ADMIN'].includes(u.role)
        )
      );
    } catch {
      /* optional for create/edit */
    }
  }, []);

  useEffect(() => {
    if (status === 'loading') return;
    if (!session) {
      router.push('/login');
      return;
    }
    if (!canView) {
      router.push('/dashboard');
      return;
    }
    fetchManagers();
  }, [status, session, canView, router, fetchManagers]);

  useEffect(() => {
    if (status !== 'authenticated' || !canView) return;
    fetchDepartments();
  }, [status, canView, fetchDepartments]);

  const openCreate = () => {
    setEditingId(null);
    setForm(EMPTY_FORM);
    setShowModal(true);
  };
  const openEdit = (d: Department) => {
    setEditingId(d.id);
    setForm({
      name: d.name,
      description: d.description || '',
      managerId: d.managerId || '',
    });
    setShowModal(true);
  };
  const closeModal = () => {
    setShowModal(false);
    setEditingId(null);
    setForm(EMPTY_FORM);
  };

  const handleSave = async () => {
    if (!form.name.trim()) {
      toast({
        title: 'Validation',
        description: 'Department name is required',
        variant: 'destructive',
      });
      return;
    }
    setSaving(true);
    try {
      const payload = {
        name: form.name.trim(),
        description: form.description.trim() || null,
        managerId: form.managerId || null,
      };
      const data = await apiCall<any>(
        api.endpoints.saveDepartment.initiate({
          id: editingId || undefined,
          body: payload,
        }),
      );
      toast({
        title: editingId ? 'Department updated' : 'Department created',
        description: data.name,
      });
      closeModal();
      fetchDepartments();
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' });
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    setDeleting(true);
    try {
      await apiCall(api.endpoints.deleteDepartment.initiate(id));
      toast({ title: 'Department deleted' });
      setDeleteConfirmId(null);
      if (departments.length === 1 && page > 1) setPage((p) => p - 1);
      else fetchDepartments();
    } catch (err: any) {
      toast({ title: 'Error', description: err.message, variant: 'destructive' });
    } finally {
      setDeleting(false);
    }
  };

  const toggleSort = (field: SortField) => {
    if (sortField === field) setSortDir((d) => (d === 'asc' ? 'desc' : 'asc'));
    else {
      setSortField(field);
      setSortDir('asc');
    }
  };

  const SortIcon = ({ field }: { field: SortField }) => {
    if (sortField !== field)
      return <ChevronDown className="h-3.5 w-3.5 text-muted-foreground/40 ml-1" />;
    return sortDir === 'asc' ? (
      <ChevronUp className="h-3.5 w-3.5 text-primary ml-1" />
    ) : (
      <ChevronDown className="h-3.5 w-3.5 text-primary ml-1" />
    );
  };

  if (status === 'loading') {
    return <OrgTablePageSkeleton />;
  }

  const deleteTarget = departments.find((d) => d.id === deleteConfirmId);

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div className="space-y-1">
          <p className="text-sm text-muted-foreground">Organisation structure</p>
          <p className="text-xs text-muted-foreground tabular-nums">
            {total} department{total !== 1 ? 's' : ''}
          </p>
        </div>
        {canManage && (
          <Button onClick={openCreate} className="gap-2 shrink-0">
            <Plus className="h-4 w-4" />
            Add department
          </Button>
        )}
      </div>

      <div className="relative max-w-sm">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder="Search departments..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>

      <div className="rounded-xl border border-border bg-card overflow-hidden shadow-sm">
        <div
          className={cn(
            'hidden md:grid gap-4 px-5 py-3 bg-muted/30 border-b border-border',
            'text-[11px] font-semibold uppercase tracking-[0.08em] text-muted-foreground',
            canManage
              ? 'grid-cols-[minmax(0,2fr)_minmax(0,1.6fr)_7rem_7rem_5.5rem]'
              : 'grid-cols-[minmax(0,2fr)_minmax(0,1.6fr)_7rem_7rem]'
          )}
        >
          <button
            type="button"
            className="flex items-center text-left hover:text-foreground transition-colors"
            onClick={() => toggleSort('name')}
          >
            Department <SortIcon field="name" />
          </button>
          <button
            type="button"
            className="flex items-center text-left hover:text-foreground transition-colors"
            onClick={() => toggleSort('manager')}
          >
            Manager <SortIcon field="manager" />
          </button>
          <button
            type="button"
            className="flex items-center text-left hover:text-foreground transition-colors"
            onClick={() => toggleSort('designations')}
          >
            Roles <SortIcon field="designations" />
          </button>
          <button
            type="button"
            className="flex items-center text-left hover:text-foreground transition-colors"
            onClick={() => toggleSort('createdAt')}
          >
            Created <SortIcon field="createdAt" />
          </button>
          {canManage && <div className="text-right">Actions</div>}
        </div>

        {loading && departments.length === 0 ? (
          <div className="flex items-center justify-center py-20">
            <AppSpinner className="h-6 w-6" />
          </div>
        ) : departments.length === 0 ? (
          <div className="py-16 text-center px-4">
            <Building2 className="h-10 w-10 text-muted-foreground/40 mx-auto mb-3" />
            <p className="text-muted-foreground text-sm">
              {debouncedSearch ? 'No departments match your search' : 'No departments yet'}
            </p>
            {canManage && !debouncedSearch && (
              <Button onClick={openCreate} variant="outline" size="sm" className="mt-3 gap-1.5">
                <Plus className="h-3.5 w-3.5" /> Add Department
              </Button>
            )}
          </div>
        ) : (
          <div className={cn(loading && 'opacity-60 pointer-events-none')}>
            {departments.map((dept) => (
              <div
                key={dept.id}
                className={cn(
                  'grid gap-3 md:gap-4 px-5 py-3.5 items-center',
                  'border-b border-border/60 last:border-b-0',
                  'hover:bg-muted/40 transition-colors',
                  canManage
                    ? 'grid-cols-1 md:grid-cols-[minmax(0,2fr)_minmax(0,1.6fr)_7rem_7rem_5.5rem]'
                    : 'grid-cols-1 md:grid-cols-[minmax(0,2fr)_minmax(0,1.6fr)_7rem_7rem]'
                )}
              >
                <div className="flex items-center gap-3 min-w-0">
                  <div className="h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0">
                    <Building2 className="h-4 w-4 text-primary" />
                  </div>
                  <div className="min-w-0">
                    <p className="font-medium text-foreground text-sm truncate">{dept.name}</p>
                    {dept.description ? (
                      <p className="text-xs text-muted-foreground truncate mt-0.5">
                        {dept.description}
                      </p>
                    ) : null}
                  </div>
                </div>

                <div className="flex items-center gap-2 min-w-0">
                  <UserCircle className="h-4 w-4 text-muted-foreground/60 flex-shrink-0 hidden md:block" />
                  {dept.manager ? (
                    <div className="min-w-0">
                      <p className="text-sm text-foreground truncate">{dept.manager.name}</p>
                      <p className="text-xs text-muted-foreground truncate">
                        {dept.manager.position}
                      </p>
                    </div>
                  ) : (
                    <span className="text-sm text-muted-foreground">—</span>
                  )}
                </div>

                <div>
                  <Badge variant="secondary" className="text-xs font-medium tabular-nums">
                    <Layers className="h-3 w-3 mr-1" />
                    {dept._count.designations}
                  </Badge>
                </div>

                <div className="text-xs text-muted-foreground tabular-nums">
                  {new Date(dept.createdAt).toLocaleDateString('en-US', {
                    day: 'numeric',
                    month: 'short',
                    year: 'numeric',
                  })}
                </div>

                {canManage && (
                  <div className="flex items-center justify-end gap-0.5">
                    <button
                      type="button"
                      onClick={() => openEdit(dept)}
                      className="p-1.5 rounded-md hover:bg-primary/10 text-muted-foreground hover:text-primary transition-colors"
                      title="Edit"
                    >
                      <Pencil className="h-4 w-4" />
                    </button>
                    <button
                      type="button"
                      onClick={() => setDeleteConfirmId(dept.id)}
                      className="p-1.5 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
                      title="Delete"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}

        <TablePagination
          currentPage={page}
          totalItems={total}
          pageSize={PAGE_SIZE}
          onPageChange={setPage}
          itemLabel="departments"
        />
      </div>

      <Dialog open={showModal} onOpenChange={(open) => !open && closeModal()}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>{editingId ? 'Edit Department' : 'Add New Department'}</DialogTitle>
            <DialogDescription>
              {editingId
                ? 'Update department details and manager assignment.'
                : 'Create a department for your organisation structure.'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 min-w-0">
            <div className="space-y-2 min-w-0">
              <Label>
                Department Name <span className="text-destructive">*</span>
              </Label>
              <Input
                placeholder="e.g. Engineering, Marketing, HR"
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
              />
            </div>
            <div className="space-y-2 min-w-0">
              <Label>Description</Label>
              <textarea
                placeholder="Brief description of this department..."
                value={form.description}
                onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))}
                rows={3}
                className="w-full max-w-full min-w-0 px-3 py-2 text-sm bg-background text-foreground border border-border rounded-md focus:outline-none focus:ring-2 focus:ring-ring resize-none"
              />
            </div>
            <div className="space-y-2 min-w-0">
              <Label>Department Manager</Label>
              <FilterSelect
                value={form.managerId || '__none__'}
                onValueChange={(v) =>
                  setForm((f) => ({ ...f, managerId: v === '__none__' ? '' : v }))
                }
                placeholder="— No manager assigned —"
                searchPlaceholder="Search managers…"
                className="w-full min-w-0 max-w-full"
                options={[
                  { value: '__none__', label: '— No manager assigned —' },
                  ...managers.map((m) => ({
                    value: m.id,
                    label: m.position ? `${m.name} · ${m.position}` : m.name,
                  })),
                ]}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={closeModal} disabled={saving} className="sm:min-w-[7rem]">
              Cancel
            </Button>
            <Button onClick={handleSave} disabled={saving} className="sm:min-w-[7rem]">
              {saving && <AppSpinner className="mr-2" />}
              {editingId ? 'Save Changes' : 'Create Department'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={!!deleteConfirmId}
        onOpenChange={(open) => !open && setDeleteConfirmId(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Department</AlertDialogTitle>
            <AlertDialogDescription>
              Department links for{' '}
              <span className="font-medium text-foreground">{deleteTarget?.name}</span> will be
              removed. Shared designations used by other departments are kept. This cannot be
              undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={(e) => {
                e.preventDefault();
                if (deleteConfirmId) handleDelete(deleteConfirmId);
              }}
              disabled={deleting}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleting && <AppSpinner className="mr-2" />}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
