'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 { Checkbox } from '@/components/ui/checkbox';
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 {
  Briefcase,
  Plus,
  Search,
  Pencil,
  Trash2,
  Building2,
  X,
  ChevronDown,
  ChevronUp,
  Filter,
} 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 Department {
  id: string;
  name: string;
}

interface Designation {
  id: string;
  title: string;
  description: string | null;
  departments: Department[];
  createdAt: string;
}

interface FormState {
  title: string;
  description: string;
  departmentIds: string[];
}

const EMPTY_FORM: FormState = { title: '', description: '', departmentIds: [] };
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 = 'title' | 'createdAt';
type SortDir = 'asc' | 'desc';

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

  const [designations, setDesignations] = useState<Designation[]>([]);
  const [departments, setDepartments] = useState<Department[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');
  const [filterDeptId, setFilterDeptId] = useState('');
  const [sortField, setSortField] = useState<SortField>('title');
  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, filterDeptId, sortField, sortDir]);

  const fetchDesignations = 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);
      if (filterDeptId) params.set('departmentId', filterDeptId);

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

  const fetchDepartments = useCallback(async () => {
    try {
      const data = await apiCall<any>(api.endpoints.getDepartments.initiate());
      setDepartments(data);
    } catch {
      /* filter dropdown optional */
    }
  }, []);

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

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

  const openCreate = () => {
    setEditingId(null);
    setForm(EMPTY_FORM);
    setShowModal(true);
  };
  const openEdit = (d: Designation) => {
    setEditingId(d.id);
    setForm({
      title: d.title,
      description: d.description || '',
      departmentIds: (d.departments || []).map((x) => x.id),
    });
    setShowModal(true);
  };
  const closeModal = () => {
    setShowModal(false);
    setEditingId(null);
    setForm(EMPTY_FORM);
  };

  const toggleDepartment = (id: string) => {
    setForm((f) => ({
      ...f,
      departmentIds: f.departmentIds.includes(id)
        ? f.departmentIds.filter((x) => x !== id)
        : [...f.departmentIds, id],
    }));
  };

  const handleSave = async () => {
    if (!form.title.trim()) {
      toast({ title: 'Validation', description: 'Title is required', variant: 'destructive' });
      return;
    }
    if (form.departmentIds.length === 0) {
      toast({
        title: 'Validation',
        description: 'Select at least one department',
        variant: 'destructive',
      });
      return;
    }
    setSaving(true);
    try {
      const payload = {
        title: form.title.trim(),
        description: form.description.trim() || null,
        departmentIds: form.departmentIds,
      };
      const data = await apiCall<any>(
        api.endpoints.saveDesignation.initiate({
          id: editingId || undefined,
          body: payload,
        }),
      );
      toast({
        title: editingId ? 'Designation updated' : 'Designation created',
        description: data.title,
      });
      closeModal();
      fetchDesignations();
    } 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.deleteDesignation.initiate(id));
      toast({ title: 'Designation deleted' });
      setDeleteConfirmId(null);
      if (designations.length === 1 && page > 1) setPage((p) => p - 1);
      else fetchDesignations();
    } 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 = designations.find((d) => d.id === deleteConfirmId);

  const duplicateTitles = (() => {
    const counts = new Map<string, number>();
    for (const d of designations) {
      const key = d.title.trim().toLowerCase();
      counts.set(key, (counts.get(key) || 0) + 1);
    }
    return Array.from(counts.entries())
      .filter(([, n]) => n > 1)
      .map(([key]) => designations.find((d) => d.title.trim().toLowerCase() === key)?.title)
      .filter(Boolean) as string[];
  })();

  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">Roles across departments</p>
          <p className="text-xs text-muted-foreground tabular-nums">
            {total} designation{total !== 1 ? 's' : ''}
            {departments.length > 0
              ? ` · ${departments.length} department${departments.length !== 1 ? 's' : ''}`
              : ''}
          </p>
        </div>
        {canManage && (
          <Button onClick={openCreate} className="gap-2 shrink-0">
            <Plus className="h-4 w-4" />
            Add designation
          </Button>
        )}
      </div>

      {duplicateTitles.length > 0 && (
        <div className="rounded-xl border border-amber-500/25 bg-amber-500/5 px-4 py-3 text-sm text-amber-900 dark:text-amber-200">
          Duplicate titles still present on this page:{' '}
          <span className="font-medium">{duplicateTitles.join(', ')}</span>. Edit one
          record to attach all needed departments, then delete the extra row(s).
        </div>
      )}

      <div className="flex flex-wrap gap-3 items-center">
        <div className="relative flex-1 min-w-[200px] 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 designations..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-9"
          />
        </div>
        <div className="flex items-center gap-2">
          <Filter className="h-4 w-4 text-muted-foreground" />
          <FilterSelect
            value={filterDeptId || 'all'}
            onValueChange={(v) => setFilterDeptId(v === 'all' ? '' : v)}
            placeholder="All Departments"
            searchPlaceholder="Search departments…"
            className="min-w-[180px]"
            options={[
              { value: 'all', label: 'All Departments' },
              ...departments.map((d) => ({ value: d.id, label: d.name })),
            ]}
          />
        </div>
        {(search || filterDeptId) && (
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setSearch('');
              setFilterDeptId('');
            }}
            className="text-muted-foreground gap-1"
          >
            <X className="h-3.5 w-3.5" /> Clear
          </Button>
        )}
      </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,1.6fr)_minmax(0,2.2fr)_minmax(0,1.4fr)_7rem_5.5rem]'
              : 'grid-cols-[minmax(0,1.6fr)_minmax(0,2.2fr)_minmax(0,1.4fr)_7rem]'
          )}
        >
          <button
            type="button"
            className="flex items-center text-left hover:text-foreground transition-colors"
            onClick={() => toggleSort('title')}
          >
            Designation <SortIcon field="title" />
          </button>
          <div>Departments</div>
          <div>Description</div>
          <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 && designations.length === 0 ? (
          <div className="flex items-center justify-center py-20">
            <AppSpinner className="h-6 w-6" />
          </div>
        ) : designations.length === 0 ? (
          <div className="py-16 text-center px-4">
            <Briefcase className="h-10 w-10 text-muted-foreground/40 mx-auto mb-3" />
            <p className="text-muted-foreground text-sm">
              {debouncedSearch || filterDeptId
                ? 'No designations match your filters'
                : 'No designations yet'}
            </p>
            {canManage && !debouncedSearch && !filterDeptId && (
              <Button onClick={openCreate} variant="outline" size="sm" className="mt-3 gap-1.5">
                <Plus className="h-3.5 w-3.5" /> Add Designation
              </Button>
            )}
          </div>
        ) : (
          <div className={cn(loading && 'opacity-60 pointer-events-none')}>
            {designations.map((desig) => (
              <div
                key={desig.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,1.6fr)_minmax(0,2.2fr)_minmax(0,1.4fr)_7rem_5.5rem]'
                    : 'grid-cols-1 md:grid-cols-[minmax(0,1.6fr)_minmax(0,2.2fr)_minmax(0,1.4fr)_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">
                    <Briefcase className="h-4 w-4 text-primary" />
                  </div>
                  <p className="font-medium text-foreground text-sm truncate">{desig.title}</p>
                </div>

                <div className="flex flex-wrap gap-1.5 min-w-0">
                  {(desig.departments || []).length === 0 ? (
                    <span className="text-xs text-muted-foreground">—</span>
                  ) : (
                    desig.departments.map((dept) => (
                      <Badge
                        key={dept.id}
                        variant="outline"
                        className="text-xs gap-1 font-normal max-w-full"
                      >
                        <Building2 className="h-3 w-3 shrink-0" />
                        <span className="truncate">{dept.name}</span>
                      </Badge>
                    ))
                  )}
                </div>

                <p className="text-xs text-muted-foreground truncate">
                  {desig.description || '—'}
                </p>

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

                {canManage && (
                  <div className="flex items-center justify-end gap-0.5">
                    <button
                      type="button"
                      onClick={() => openEdit(desig)}
                      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(desig.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="designations"
        />
      </div>

      <Dialog open={showModal} onOpenChange={(open) => !open && closeModal()}>
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>
              {editingId ? 'Edit Designation' : 'Add New Designation'}
            </DialogTitle>
            <DialogDescription>
              One designation can be linked to multiple departments and reused
              across the organisation. Prefer editing an existing title to add
              departments instead of creating duplicates.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 min-w-0">
            <div className="space-y-2 min-w-0">
              <Label>
                Designation Title <span className="text-destructive">*</span>
              </Label>
              <Input
                placeholder="e.g. Team Lead, Senior Software Engineer"
                value={form.title}
                onChange={(e) => setForm((f) => ({ ...f, title: e.target.value }))}
              />
            </div>
            <div className="space-y-2 min-w-0">
              <Label>
                Departments <span className="text-destructive">*</span>
              </Label>
              <div className="max-h-48 overflow-y-auto rounded-lg border border-border p-2 space-y-1">
                {departments.length === 0 ? (
                  <p className="text-xs text-muted-foreground px-2 py-3">No departments found</p>
                ) : (
                  departments.map((d) => {
                    const checked = form.departmentIds.includes(d.id);
                    return (
                      <label
                        key={d.id}
                        className={cn(
                          'flex items-center gap-2.5 rounded-md px-2 py-1.5 text-sm cursor-pointer hover:bg-muted/50',
                          checked && 'bg-primary/5'
                        )}
                      >
                        <Checkbox
                          checked={checked}
                          onCheckedChange={() => toggleDepartment(d.id)}
                        />
                        <span className="truncate">{d.name}</span>
                      </label>
                    );
                  })
                )}
              </div>
              <p className="text-xs text-muted-foreground">
                {form.departmentIds.length} department
                {form.departmentIds.length !== 1 ? 's' : ''} selected
              </p>
            </div>
            <div className="space-y-2 min-w-0">
              <Label>Description</Label>
              <textarea
                placeholder="Brief description of this role..."
                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>
          <DialogFooter>
            <Button variant="outline" onClick={closeModal} disabled={saving}>
              Cancel
            </Button>
            <Button onClick={handleSave} disabled={saving}>
              {saving && <AppSpinner className="mr-2" />}
              {editingId ? 'Save Changes' : 'Create Designation'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={!!deleteConfirmId}
        onOpenChange={(open) => !open && setDeleteConfirmId(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete Designation</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete{' '}
              <span className="font-medium text-foreground">{deleteTarget?.title}</span>? Users
              keep their current position text; this only removes the designation
              record from management.
            </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>
  );
}
