"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import {
  ArrowLeft,
  User,
  Building2,
  ChevronDown,
  Search,
  FileText,
  UploadCloud,
  X,
  Eye,
  Trash2,
  CheckCircle2,
  ClipboardList,
} from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
import { Badge } from "@/components/ui/badge";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  useAdminGetTask,
  useAdminUpdateTask,
  useAdminEmployeesByDepartment,
  useAdminUploadTaskDocuments,
  useAdminDeleteTaskDocument,
} from "../hooks/task.hooks";
import { useGetDepartments } from "@/modules/admin/departments/hooks/department.hook";
import {
  AdminUpdateTaskPayload,
  Priority,
  TaskStatus,
} from "../types/task.type";

const TASK_STATUSES: { label: string; value: TaskStatus }[] = [
  { label: "Pending", value: "PENDING" },
  { label: "In Progress", value: "IN_PROGRESS" },
  { label: "Employee Done", value: "EMPLOYEE_DONE" },
  { label: "Manager Approval", value: "MANAGER_APPROVAL" },
  { label: "Client Approval", value: "CLIENT_APPROVAL" },
  { label: "Filing Pending", value: "FILING_PENDING" },
  { label: "Completed", value: "COMPLETED" },
  { label: "Rejected", value: "REJECTED" },
];

const PRIORITIES: { label: string; value: Priority }[] = [
  { label: "Low", value: "LOW" },
  { label: "Medium", value: "MEDIUM" },
  { label: "High", value: "HIGH" },
  { label: "Urgent", value: "URGENT" },
];

function useDebounce(delay = 400) {
  const [debounced, setDebounced] = useState("");
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const update = (v: string) => {
    if (timer.current) clearTimeout(timer.current);
    timer.current = setTimeout(() => setDebounced(v), delay);
  };
  return [debounced, update] as const;
}

function SearchDropdown({
  label,
  required,
  placeholder,
  value,
  displayValue,
  open,
  onOpenChange,
  searchValue,
  onSearchChange,
  searchPlaceholder,
  children,
  disabled,
}: {
  label: string;
  required?: boolean;
  placeholder: string;
  value: string;
  displayValue?: React.ReactNode;
  open: boolean;
  onOpenChange: (v: boolean) => void;
  searchValue: string;
  onSearchChange: (v: string) => void;
  searchPlaceholder?: string;
  children: React.ReactNode;
  disabled?: boolean;
}) {
  return (
    <div className="space-y-1.5">
      <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
        {label} {required && <span className="text-destructive">*</span>}
      </Label>
      <Popover open={open} onOpenChange={onOpenChange}>
        <PopoverTrigger asChild>
          <button
            type="button"
            disabled={disabled}
            className={`w-full flex items-center justify-between gap-2 h-9 px-3 rounded-md border border-input bg-background text-sm transition-colors hover:bg-accent/50 focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50 disabled:cursor-not-allowed ${
              open ? "ring-2 ring-ring" : ""
            }`}
          >
            <span
              className={`truncate ${!value ? "text-muted-foreground" : ""}`}
            >
              {value ? displayValue : placeholder}
            </span>
            <ChevronDown
              className={`w-4 h-4 text-muted-foreground shrink-0 transition-transform ${
                open ? "rotate-180" : ""
              }`}
            />
          </button>
        </PopoverTrigger>
        <PopoverContent
          className="p-0 w-[var(--radix-popover-trigger-width)] min-w-[220px]"
          align="start"
          sideOffset={4}
        >
          <div className="p-2 border-b">
            <div className="relative">
              <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none" />
              <input
                autoFocus
                className="w-full pl-8 pr-3 py-1.5 text-sm bg-background border border-border rounded-md outline-none focus:ring-1 focus:ring-primary"
                placeholder={searchPlaceholder ?? "Search..."}
                value={searchValue}
                onChange={(e) => onSearchChange(e.target.value)}
              />
            </div>
          </div>
          <div className="max-h-56 overflow-y-auto py-1">{children}</div>
        </PopoverContent>
      </Popover>
    </div>
  );
}

function DropdownItem({
  selected,
  onClick,
  children,
}: {
  selected?: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <div
      onClick={onClick}
      className={`flex items-center gap-2 px-3 py-2 cursor-pointer text-sm hover:bg-accent transition-colors ${
        selected ? "bg-accent/70 font-medium" : ""
      }`}
    >
      {children}
    </div>
  );
}

export function EditTask({ taskId }: { taskId: string }) {
  const router = useRouter();
  const { data: task, isLoading } = useAdminGetTask(taskId);
  const { data: departmentsRes } = useGetDepartments({ page: 1, limit: 100 });
  const departments = departmentsRes?.data ?? [];

  const [step, setStep] = useState<1 | 2>(1);
  const [form, setForm] = useState<
    AdminUpdateTaskPayload & { departmentId?: string }
  >({});

  // Derived values: always fall back to task data so selects never get undefined
  const statusValue = (form.status ?? task?.status ?? "") as TaskStatus | "";
  const priorityValue = (form.priority ?? task?.priority ?? "") as
    | Priority
    | "";

  const [deptOpen, setDeptOpen] = useState(false);
  const [deptSearch, setDeptSearch] = useState("");
  const [empOpen, setEmpOpen] = useState(false);
  const [empSearchInput, setEmpSearchInput] = useState("");
  const [empSearch, updateEmpSearch] = useDebounce();

  // const { data: deptEmployees = [], isFetching: empFetching } =
  //   useAdminEmployeesByDepartment(
  //     form.departmentId ?? "",
  //     empSearch.length >= 3 ? empSearch : ""
  //   );

  const { data: deptEmployeesRaw = [], isFetching: empFetching } =
    useAdminEmployeesByDepartment(
      form.departmentId ?? "",
      empSearch.length >= 3 ? empSearch : ""
    );

  const deptEmployees = deptEmployeesRaw.filter((e) => e.role === "EMPLOYEE");

  const { mutate: updateTask, isPending } = useAdminUpdateTask(() =>
    router.push("/admin/tasks")
  );
  const uploadDocs = useAdminUploadTaskDocuments(taskId);
  const deleteDoc = useAdminDeleteTaskDocument(taskId);
  const [deleteConfirmDocId, setDeleteConfirmDocId] = useState<string | null>(
    null
  );

  useEffect(() => {
    if (!task) return;
    setForm({
      status: task.status,
      priority: task.priority,
      assignedEmployeeId: task.assignedEmployee?.id ?? "",
      departmentId: task.department?.id ?? "",
      dueDate: task.dueDate ? task.dueDate.slice(0, 10) : "",
      title: task.title,
      description: task.description ?? "",
    });
  }, [task]);

  const handleEmpSearch = (v: string) => {
    setEmpSearchInput(v);
    if (v.length === 0 || v.length >= 3) updateEmpSearch(v);
  };

  const handleDeptSelect = (id: string) => {
    setForm((p) => ({ ...p, departmentId: id, assignedEmployeeId: "" }));
    setDeptOpen(false);
    setEmpSearchInput("");
    updateEmpSearch("");
  };

  const handleEmpSelect = (id: string) => {
    setForm((p) => ({ ...p, assignedEmployeeId: id }));
    setEmpOpen(false);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const payload: AdminUpdateTaskPayload = {};
    if (form.status) payload.status = form.status;
    if (form.priority) payload.priority = form.priority;
    payload.assignedEmployeeId = form.assignedEmployeeId || undefined;
    payload.departmentId = form.departmentId || undefined;
    if (form.dueDate !== undefined) payload.dueDate = form.dueDate || undefined;
    if (form.title?.trim()) payload.title = form.title.trim();
    if (form.description !== undefined) payload.description = form.description;
    updateTask({ taskId, payload });
  };

  const filteredDepts =
    deptSearch.length >= 3
      ? departments.filter((d) =>
          d.name.toLowerCase().includes(deptSearch.toLowerCase())
        )
      : departments;

  const selectedDept = departments.find((d) => d.id === form.departmentId);
  const selectedEmp =
    deptEmployees.find((e) => e.id === form.assignedEmployeeId) ??
    (task?.assignedEmployee?.id === form.assignedEmployeeId
      ? task?.assignedEmployee
      : null);

  if (isLoading) {
    return (
      <div className="space-y-4">
        {[1, 2, 3].map((i) => (
          <Skeleton key={i} className="h-16 w-full rounded-xl" />
        ))}
      </div>
    );
  }

  if (!task)
    return <p className="text-muted-foreground text-sm">Task not found.</p>;

  return (
    <div className="space-y-6 w-full">
      {/* Header */}
      <div className="flex items-center gap-3">
        <button
          onClick={() => router.back()}
          className="text-muted-foreground hover:text-foreground flex items-center gap-1 text-sm"
        >
          <ArrowLeft className="h-4 w-4" /> Back
        </button>
      </div>
      <div>
        <h2 className="text-xl font-bold tracking-tight">Edit Task</h2>
        <p className="text-muted-foreground text-sm">
          {task.client.name} · {task.service.name}
        </p>
      </div>

      {/* Step Indicator */}
      <div className="flex items-center">
        <div className="flex items-center gap-2">
          <div
            className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold shrink-0 transition-colors ${
              step === 1
                ? "bg-primary text-primary-foreground"
                : "bg-green-500 text-white"
            }`}
          >
            {step > 1 ? <CheckCircle2 className="w-4 h-4" /> : "1"}
          </div>
          <span
            className={`text-sm font-medium whitespace-nowrap ${
              step === 1 ? "text-foreground" : "text-muted-foreground"
            }`}
          >
            Task Info
          </span>
        </div>
        <div
          className={`flex-1 h-px mx-3 transition-colors ${
            step > 1 ? "bg-green-500" : "bg-border"
          }`}
        />
        <div className="flex items-center gap-2">
          <div
            className={`w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold shrink-0 transition-colors ${
              step === 2
                ? "bg-primary text-primary-foreground"
                : "bg-muted text-muted-foreground"
            }`}
          >
            2
          </div>
          <span
            className={`text-sm font-medium whitespace-nowrap ${
              step === 2 ? "text-foreground" : "text-muted-foreground"
            }`}
          >
            Assignment & Documents
          </span>
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-4">
        {/* ── STEP 1 ── */}
        {step === 1 && (
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="flex items-center gap-2 text-base">
                <ClipboardList className="h-4 w-4 text-primary" /> Task Info
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-1.5">
                <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  Title
                </Label>
                <Input
                  value={form.title ?? ""}
                  onChange={(e) =>
                    setForm((p) => ({ ...p, title: e.target.value }))
                  }
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Status
                  </Label>
                  <Select
                    value={statusValue}
                    onValueChange={(v) =>
                      setForm((p) => ({ ...p, status: v as TaskStatus }))
                    }
                    disabled={task.status === "COMPLETED"}
                  >
                    {task?.status === "COMPLETED" && (
                      <p className="text-[11px] text-amber-600">
                        Task completed & paid — status is locked.
                      </p>
                    )}
                    <SelectTrigger>
                      <SelectValue placeholder="Select status" />
                    </SelectTrigger>
                    <SelectContent>
                      {TASK_STATUSES.map((s) => (
                        <SelectItem key={s.value} value={s.value}>
                          {s.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1.5">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Priority
                  </Label>
                  <Select
                    value={priorityValue}
                    onValueChange={(v) =>
                      setForm((p) => ({ ...p, priority: v as Priority }))
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Select priority" />
                    </SelectTrigger>
                    <SelectContent>
                      {PRIORITIES.map((p) => (
                        <SelectItem key={p.value} value={p.value}>
                          {p.label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-1.5 max-w-[11rem]">
                  <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                    Due Date
                  </Label>
                  <Input
                    type="date"
                    value={form.dueDate ?? ""}
                    onChange={(e) =>
                      setForm((p) => ({ ...p, dueDate: e.target.value }))
                    }
                  />
                </div>
              </div>

              <div className="space-y-1.5">
                <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                  Description
                </Label>
                <Textarea
                  value={form.description ?? ""}
                  onChange={(e) =>
                    setForm((p) => ({ ...p, description: e.target.value }))
                  }
                  rows={3}
                  className="resize-none"
                />
              </div>

              <div className="flex items-center justify-end gap-3 pt-1">
                <Button
                  type="button"
                  variant="ghost"
                  className="border border-border hover:bg-muted hover:text-foreground"
                  onClick={() => router.back()}
                >
                  Cancel
                </Button>
                <Button type="button" onClick={() => setStep(2)}>
                  Next <span className="ml-1.5">→</span>
                </Button>
              </div>
            </CardContent>
          </Card>
        )}

        {/* ── STEP 2 ── */}
        {step === 2 && (
          <div className="space-y-4">
            {/* Summary */}

            {/* Assignment */}
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="flex items-center gap-2 text-base">
                  <Building2 className="h-4 w-4 text-primary" /> Assignment
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <SearchDropdown
                    label="Department"
                    required
                    placeholder="Select department"
                    value={form.departmentId ?? ""}
                    displayValue={
                      selectedDept ? (
                        <span className="flex items-center gap-1.5">
                          <Building2 className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
                          {selectedDept.name}
                        </span>
                      ) : undefined
                    }
                    open={deptOpen}
                    onOpenChange={setDeptOpen}
                    searchValue={deptSearch}
                    onSearchChange={setDeptSearch}
                    searchPlaceholder="Search department..."
                  >
                    {filteredDepts.length === 0 ? (
                      <div className="px-3 py-5 text-center text-sm text-muted-foreground">
                        {deptSearch.length > 0 && deptSearch.length < 3 ? (
                          <span>
                            Type <strong>3+</strong> characters to search
                          </span>
                        ) : (
                          "No departments found"
                        )}
                      </div>
                    ) : (
                      <>
                        <DropdownItem
                          selected={!form.departmentId}
                          onClick={() => handleDeptSelect("")}
                        >
                          <span className="text-muted-foreground">
                            — Unassigned
                          </span>
                        </DropdownItem>
                        {filteredDepts.map((d) => (
                          <DropdownItem
                            key={d.id}
                            selected={form.departmentId === d.id}
                            onClick={() => handleDeptSelect(d.id)}
                          >
                            <Building2 className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
                            <span className="truncate">{d.name}</span>
                          </DropdownItem>
                        ))}
                      </>
                    )}
                  </SearchDropdown>

                  <SearchDropdown
                    label="Assign Employee"
                    placeholder={
                      form.departmentId
                        ? "Select employee"
                        : "Select department first"
                    }
                    value={form.assignedEmployeeId ?? ""}
                    displayValue={
                      selectedEmp ? (
                        <span className="flex items-center gap-1.5">
                          <User className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
                          {selectedEmp.name}
                        </span>
                      ) : undefined
                    }
                    open={empOpen}
                    onOpenChange={setEmpOpen}
                    searchValue={empSearchInput}
                    onSearchChange={handleEmpSearch}
                    searchPlaceholder="Search by name, email..."
                    disabled={!form.departmentId}
                  >
                    {empFetching ? (
                      <div className="px-3 py-4 text-sm text-muted-foreground text-center">
                        Loading...
                      </div>
                    ) : deptEmployees.length === 0 ? (
                      <div className="px-3 py-5 text-center text-sm text-muted-foreground">
                        {empSearchInput.length > 0 &&
                        empSearchInput.length < 3 ? (
                          <span>
                            Type <strong>3+</strong> characters to search
                          </span>
                        ) : (
                          "No active employees in this department"
                        )}
                      </div>
                    ) : (
                      <>
                        <DropdownItem
                          selected={!form.assignedEmployeeId}
                          onClick={() => handleEmpSelect("")}
                        >
                          <span className="text-muted-foreground">
                            — Unassigned
                          </span>
                        </DropdownItem>
                        {deptEmployees.map((emp) => (
                          <DropdownItem
                            key={emp.id}
                            selected={form.assignedEmployeeId === emp.id}
                            onClick={() => handleEmpSelect(emp.id)}
                          >
                            <User className="w-3.5 h-3.5 text-muted-foreground shrink-0" />
                            <div className="min-w-0 flex-1">
                              <p className="truncate">{emp.name}</p>
                              <p className="text-xs text-muted-foreground truncate">
                                {emp.email}
                              </p>
                            </div>
                            <Badge
                              variant="outline"
                              className="text-[10px] shrink-0"
                            >
                              {emp.role}
                            </Badge>
                          </DropdownItem>
                        ))}
                      </>
                    )}
                  </SearchDropdown>
                </div>
              </CardContent>
            </Card>

            {/* Documents */}
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-sm flex items-center justify-between">
                  <span className="flex items-center gap-2">
                    <FileText className="h-4 w-4 text-primary" />
                    Documents
                    {task.documents?.length > 0 && (
                      <span className="text-xs font-normal text-muted-foreground">
                        ({task.documents.length})
                      </span>
                    )}
                  </span>
                  <label className="flex items-center gap-1.5 text-xs font-medium text-primary border border-primary/30 bg-primary/5 hover:bg-primary/10 rounded-md px-3 py-1.5 cursor-pointer transition-colors">
                    <UploadCloud className="w-3.5 h-3.5" />
                    {uploadDocs.isPending ? "Uploading..." : "Upload"}
                    <input
                      type="file"
                      multiple
                      hidden
                      disabled={uploadDocs.isPending}
                      onChange={(e) => {
                        const files = Array.from(e.target.files ?? []);
                        if (files.length) uploadDocs.mutate(files);
                        e.target.value = "";
                      }}
                    />
                  </label>
                </CardTitle>
              </CardHeader>
              <CardContent>
                {!task.documents?.length ? (
                  <div className="flex flex-col items-center gap-2 rounded-xl border border-dashed p-8 text-center">
                    <FileText className="w-7 h-7 text-muted-foreground/30" />
                    <p className="text-sm text-muted-foreground">
                      No documents yet
                    </p>
                  </div>
                ) : (
                  <div className="space-y-2">
                    {task.documents.map((doc) => (
                      <div
                        key={doc.id}
                        className="flex items-center gap-3 rounded-lg border px-3 py-2.5 bg-muted/20"
                      >
                        <FileText className="w-4 h-4 text-muted-foreground shrink-0" />
                        <div className="min-w-0 flex-1">
                          <p className="text-sm font-medium truncate">
                            {doc.fileName}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {doc.fileSizeKb
                              ? doc.fileSizeKb < 1024
                                ? `${doc.fileSizeKb} KB`
                                : `${(doc.fileSizeKb / 1024).toFixed(1)} MB`
                              : ""}
                            {(doc as any).serviceDocument?.name &&
                              ` · ${(doc as any).serviceDocument.name}`}
                          </p>
                        </div>
                        <div className="flex items-center gap-1 shrink-0">
                          <Button
                            size="icon"
                            variant="ghost"
                            className="h-7 w-7 text-muted-foreground hover:text-primary"
                            asChild
                          >
                            <a
                              href={doc.fileUrl}
                              target="_blank"
                              rel="noopener noreferrer"
                            >
                              <Eye className="h-3.5 w-3.5" />
                            </a>
                          </Button>

                          {deleteConfirmDocId === doc.id ? (
                            <>
                              <Button
                                type="button"
                                size="icon"
                                variant="ghost"
                                className="h-7 w-7 text-red-600 hover:bg-red-500/10"
                                disabled={deleteDoc.isPending}
                                onClick={() => {
                                  deleteDoc.mutate(doc.id);
                                  setDeleteConfirmDocId(null);
                                }}
                              >
                                <Trash2 className="h-3.5 w-3.5" />
                              </Button>
                              <Button
                                type="button"
                                size="icon"
                                variant="ghost"
                                className="h-7 w-7 text-muted-foreground"
                                onClick={() => setDeleteConfirmDocId(null)}
                              >
                                <X className="h-3.5 w-3.5" />
                              </Button>
                            </>
                          ) : (
                            <Button
                              type="button"
                              size="icon"
                              variant="ghost"
                              className="h-7 w-7 text-muted-foreground hover:text-red-600 hover:bg-red-500/10"
                              onClick={() => setDeleteConfirmDocId(doc.id)}
                            >
                              <Trash2 className="h-3.5 w-3.5" />
                            </Button>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </CardContent>
            </Card>
            <div className="flex items-center justify-end gap-3 pt-1">
              <Button
                type="button"
                variant="ghost"
                className="h-10 px-4 border border-border hover:bg-muted hover:text-foreground"
                onClick={() => setStep(1)}
              >
                Back
              </Button>

              <Button type="submit" disabled={isPending}>
                {isPending && (
                  <span className="w-4 h-4 border-2 border-primary-foreground border-t-transparent rounded-full animate-spin mr-2" />
                )}
                Save Changes
              </Button>
            </div>
          </div>
        )}
      </form>
    </div>
  );
}
