/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useMemo } from "react";
import { Employee, DelegatedTask, DelegatedTaskSubItem, AuditLog } from "../types";
import { 
  CheckSquare, 
  Plus, 
  Trash2, 
  Search, 
  Filter, 
  CheckCircle2, 
  Clock, 
  AlertCircle, 
  UserCheck, 
  Sparkles, 
  Send, 
  Calendar, 
  Briefcase, 
  Edit2, 
  ChevronRight, 
  Building2, 
  ShieldCheck, 
  Bell, 
  Check, 
  X,
  Layers,
  ArrowUpRight
} from "lucide-react";

interface EmployeeDelegationTabProps {
  employee: Employee;
  employees: Employee[];
  currentUser?: Employee | null;
  onUpdateDelegatedTasks: (tasks: DelegatedTask[]) => void;
  onAddAuditLog?: (empId: string, log: Omit<AuditLog, "id" | "timestamp">) => void;
}

const DEFAULT_BUSINESS_UNITS = [
  "PT Global Synergy (Holding Corporate)",
  "EMD Tech & SaaS Solutions (Client A)",
  "Retail & Store Network (Client B)",
  "Logistik & Supply Chain (Client C)",
  "HR & People Operations",
  "Keuangan & General Audit"
];

export function EmployeeDelegationTab({
  employee,
  employees,
  currentUser,
  onUpdateDelegatedTasks,
  onAddAuditLog
}: EmployeeDelegationTabProps) {
  // Main tasks state
  const tasks = useMemo(() => employee.delegatedTasks || [], [employee.delegatedTasks]);

  // Filter & Search states
  const [searchTerm, setSearchTerm] = useState<string>("");
  const [selectedCategory, setSelectedCategory] = useState<string>("ALL");
  const [selectedPriority, setSelectedPriority] = useState<string>("ALL");
  const [selectedStatus, setSelectedStatus] = useState<string>("ALL");

  // Notification Toast state for automated supervisor updates
  const [autoNotificationToast, setAutoNotificationToast] = useState<{
    taskTitle: string;
    supervisorName: string;
    completedAt: string;
  } | null>(null);

  // Modal State: Create / Edit Delegated Task
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [editingTask, setEditingTask] = useState<DelegatedTask | null>(null);

  // Form inputs for task creation/editing
  const [taskTitle, setTaskTitle] = useState<string>("");
  const [taskDescription, setTaskDescription] = useState<string>("");
  const [taskPriority, setTaskPriority] = useState<'High' | 'Medium' | 'Low'>("Medium");
  const [taskCategory, setTaskCategory] = useState<string>(DEFAULT_BUSINESS_UNITS[0]);
  const [customCategoryInput, setCustomCategoryInput] = useState<string>("");
  const [isCustomCategory, setIsCustomCategory] = useState<boolean>(false);
  const [taskDueDate, setTaskDueDate] = useState<string>(() => {
    const d = new Date();
    d.setDate(d.getDate() + 7);
    return d.toISOString().split("T")[0];
  });
  const [taskAssignedBy, setTaskAssignedBy] = useState<string>(
    currentUser ? `${currentUser.name} (${currentUser.position})` : "Manager Operasional HR"
  );
  
  // Find default supervisor for this employee
  const defaultSupervisor = useMemo(() => {
    if (!employee.reportingTo || employee.reportingTo === "none") {
      return employees.find(e => e.position.includes("CEO") || e.position.includes("Direktur")) || null;
    }
    return employees.find(e => e.id === employee.reportingTo || e.nip === employee.reportingTo) || null;
  }, [employee.reportingTo, employees]);

  const [supervisorId, setSupervisorId] = useState<string>(
    defaultSupervisor ? defaultSupervisor.id : ""
  );

  // Sub-tasks inputs for Modal
  const [subTasksList, setSubTasksList] = useState<string[]>([
    "Review instruksi & dokumen acuan",
    "Eksekusi pengerjaan sub-tugas utama"
  ]);
  const [newSubTaskInput, setNewSubTaskInput] = useState<string>("");

  // In-line subtask addition for existing card
  const [inlineSubTaskText, setInlineSubTaskText] = useState<{ [taskId: string]: string }>({});

  // Get unique categories for filter dropdown
  const availableCategories = useMemo(() => {
    const set = new Set<string>(DEFAULT_BUSINESS_UNITS);
    tasks.forEach(t => {
      if (t.category) set.add(t.category);
    });
    return Array.from(set);
  }, [tasks]);

  // Statistics calculation
  const stats = useMemo(() => {
    const total = tasks.length;
    const completed = tasks.filter(t => t.status === "Completed").length;
    const inProgress = tasks.filter(t => t.status === "In Progress").length;
    const pending = tasks.filter(t => t.status === "Pending").length;
    const notifiedCount = tasks.filter(t => t.supervisorNotified).length;

    return { total, completed, inProgress, pending, notifiedCount };
  }, [tasks]);

  // Filtered tasks list
  const filteredTasks = useMemo(() => {
    return tasks.filter(t => {
      const matchSearch = t.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          t.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
                          t.assignedBy.toLowerCase().includes(searchTerm.toLowerCase());
      const matchCat = selectedCategory === "ALL" || t.category === selectedCategory;
      const matchPrio = selectedPriority === "ALL" || t.priority === selectedPriority;
      const matchStat = selectedStatus === "ALL" || t.status === selectedStatus;

      return matchSearch && matchCat && matchPrio && matchStat;
    });
  }, [tasks, searchTerm, selectedCategory, selectedPriority, selectedStatus]);

  // Helper: Open Modal for Create
  const handleOpenCreateModal = () => {
    setEditingTask(null);
    setTaskTitle("");
    setTaskDescription("");
    setTaskPriority("Medium");
    setTaskCategory(DEFAULT_BUSINESS_UNITS[0]);
    setIsCustomCategory(false);
    setCustomCategoryInput("");
    setTaskAssignedBy(currentUser ? `${currentUser.name} (${currentUser.position})` : "Manager Operasional HR");
    setSupervisorId(defaultSupervisor ? defaultSupervisor.id : "");
    setSubTasksList([
      "Pemeriksaan berkas & prasyarat awal",
      "Pengerjaan & validasi lapangan / sistem",
      "Pelaporan hasil akhir ke supervisor"
    ]);
    setIsModalOpen(true);
  };

  // Helper: Open Modal for Edit
  const handleOpenEditModal = (task: DelegatedTask) => {
    setEditingTask(task);
    setTaskTitle(task.title);
    setTaskDescription(task.description);
    setTaskPriority(task.priority);
    
    if (DEFAULT_BUSINESS_UNITS.includes(task.category)) {
      setTaskCategory(task.category);
      setIsCustomCategory(false);
    } else {
      setIsCustomCategory(true);
      setCustomCategoryInput(task.category);
    }

    setTaskDueDate(task.dueDate);
    setTaskAssignedBy(task.assignedBy);
    setSupervisorId(task.supervisorId || "");
    setSubTasksList(task.subTasks.map(st => st.title));
    setIsModalOpen(true);
  };

  // Helper: Add subtask item in modal
  const handleAddSubTaskInModal = () => {
    if (!newSubTaskInput.trim()) return;
    setSubTasksList(prev => [...prev, newSubTaskInput.trim()]);
    setNewSubTaskInput("");
  };

  // Helper: Remove subtask item in modal
  const handleRemoveSubTaskInModal = (index: number) => {
    setSubTasksList(prev => prev.filter((_, i) => i !== index));
  };

  // Trigger automated notification to supervisor
  const triggerSupervisorNotification = (taskTitle: string, supervisorName: string) => {
    const nowStr = new Date().toISOString().replace("T", " ").substring(0, 16);
    
    // Set UI toast
    setAutoNotificationToast({
      taskTitle,
      supervisorName,
      completedAt: nowStr
    });

    // Auto log to audit trail
    if (onAddAuditLog) {
      onAddAuditLog(employee.id, {
        action: "UPDATE",
        category: "KPI",
        actorName: currentUser ? currentUser.name : employee.name,
        actorPosition: currentUser ? currentUser.position : employee.position,
        details: `[AUTOMATED SUPERVISOR NOTIFICATION] Tugas delegasi "${taskTitle}" diselesaikan 100% oleh ${employee.name}. Notifikasi status otomatis terkirim ke Supervisor (${supervisorName}).`
      });
    }

    setTimeout(() => {
      setAutoNotificationToast(null);
    }, 6000);
  };

  // Save Task (Create or Update)
  const handleSaveTaskForm = (e: React.FormEvent) => {
    e.preventDefault();
    if (!taskTitle.trim()) return;

    const finalCategory = isCustomCategory ? (customCategoryInput.trim() || "Unit Bisnis Lainnya") : taskCategory;
    const supervisorObj = employees.find(e => e.id === supervisorId) || defaultSupervisor;
    const supName = supervisorObj ? supervisorObj.name : "Direct Supervisor";
    const nowStr = new Date().toISOString().replace("T", " ").substring(0, 16);

    if (editingTask) {
      // Update existing task
      const updatedTasks = tasks.map(t => {
        if (t.id !== editingTask.id) return t;

        // Map subtasks preserving existing completed boolean
        const updatedSubTasks: DelegatedTaskSubItem[] = subTasksList.map((stTitle, idx) => {
          const existing = t.subTasks.find(s => s.title === stTitle);
          return {
            id: existing ? existing.id : `sub-${Date.now()}-${idx}`,
            title: stTitle,
            completed: existing ? existing.completed : false
          };
        });

        return {
          ...t,
          title: taskTitle.trim(),
          description: taskDescription.trim(),
          priority: taskPriority,
          category: finalCategory,
          dueDate: taskDueDate,
          assignedBy: taskAssignedBy,
          supervisorId: supervisorId,
          supervisorName: supName,
          subTasks: updatedSubTasks
        };
      });

      onUpdateDelegatedTasks(updatedTasks);

      if (onAddAuditLog) {
        onAddAuditLog(employee.id, {
          action: "UPDATE",
          category: "Jabatan",
          actorName: currentUser ? currentUser.name : "Manager",
          actorPosition: currentUser ? currentUser.position : "Manager Operasional",
          details: `Pembaruan delegasi tugas "${taskTitle}" (Kategori: ${finalCategory}, Target: ${taskDueDate}).`
        });
      }
    } else {
      // Create new task
      const newSubTasks: DelegatedTaskSubItem[] = subTasksList.map((stTitle, idx) => ({
        id: `sub-${Date.now()}-${idx}`,
        title: stTitle,
        completed: false
      }));

      const newTask: DelegatedTask = {
        id: `del-${Date.now()}`,
        title: taskTitle.trim(),
        description: taskDescription.trim(),
        assignedBy: taskAssignedBy,
        assignedTo: employee.id,
        supervisorId: supervisorId,
        supervisorName: supName,
        priority: taskPriority,
        category: finalCategory,
        dueDate: taskDueDate,
        status: "Pending",
        subTasks: newSubTasks,
        createdAt: nowStr,
        supervisorNotified: false
      };

      const updatedTasks = [newTask, ...tasks];
      onUpdateDelegatedTasks(updatedTasks);

      if (onAddAuditLog) {
        onAddAuditLog(employee.id, {
          action: "CREATE",
          category: "Jabatan",
          actorName: currentUser ? currentUser.name : "Manager",
          actorPosition: currentUser ? currentUser.position : "Manager Operasional",
          details: `Penugasan delegasi baru "${taskTitle}" kepada pegawai ${employee.name} (${newSubTasks.length} sub-tugas, Kategori: ${finalCategory}). Notifikasi supervisor: ${supName}.`
        });
      }
    }

    setIsModalOpen(false);
  };

  // Toggle Subtask Completion
  const handleToggleSubTask = (taskId: string, subTaskId: string) => {
    let justCompletedOverall = false;
    let completedTaskTitle = "";
    let targetSupervisorName = "";

    const updatedTasks = tasks.map(t => {
      if (t.id !== taskId) return t;

      const updatedSubTasks = t.subTasks.map(st => {
        if (st.id !== subTaskId) return st;
        return { ...st, completed: !st.completed };
      });

      const totalSub = updatedSubTasks.length;
      const completedCount = updatedSubTasks.filter(s => s.completed).length;
      const allDone = totalSub > 0 && completedCount === totalSub;

      let nextStatus = t.status;
      let isNotified = t.supervisorNotified;
      let completedAt = t.completedAt;

      if (allDone && t.status !== "Completed") {
        nextStatus = "Completed";
        isNotified = true;
        completedAt = new Date().toISOString().replace("T", " ").substring(0, 16);
        justCompletedOverall = true;
        completedTaskTitle = t.title;
        targetSupervisorName = t.supervisorName || defaultSupervisor?.name || "Direct Supervisor";
      } else if (!allDone && t.status === "Completed") {
        nextStatus = "In Progress";
        isNotified = false;
        completedAt = undefined;
      } else if (completedCount > 0 && t.status === "Pending") {
        nextStatus = "In Progress";
      }

      return {
        ...t,
        subTasks: updatedSubTasks,
        status: nextStatus as any,
        supervisorNotified: isNotified,
        completedAt: completedAt
      };
    });

    onUpdateDelegatedTasks(updatedTasks);

    if (justCompletedOverall) {
      triggerSupervisorNotification(completedTaskTitle, targetSupervisorName);
    }
  };

  // Quick Change Main Task Status
  const handleStatusChange = (taskId: string, newStatus: 'Pending' | 'In Progress' | 'Completed' | 'Cancelled') => {
    let justCompletedOverall = false;
    let completedTaskTitle = "";
    let targetSupervisorName = "";

    const updatedTasks = tasks.map(t => {
      if (t.id !== taskId) return t;

      let updatedSubTasks = t.subTasks;
      let isNotified = t.supervisorNotified;
      let completedAt = t.completedAt;

      if (newStatus === "Completed") {
        // Mark all subtasks complete automatically
        updatedSubTasks = t.subTasks.map(st => ({ ...st, completed: true }));
        if (!t.supervisorNotified) {
          isNotified = true;
          completedAt = new Date().toISOString().replace("T", " ").substring(0, 16);
          justCompletedOverall = true;
          completedTaskTitle = t.title;
          targetSupervisorName = t.supervisorName || defaultSupervisor?.name || "Direct Supervisor";
        }
      }

      return {
        ...t,
        status: newStatus,
        subTasks: updatedSubTasks,
        supervisorNotified: isNotified,
        completedAt: completedAt
      };
    });

    onUpdateDelegatedTasks(updatedTasks);

    if (justCompletedOverall) {
      triggerSupervisorNotification(completedTaskTitle, targetSupervisorName);
    }
  };

  // Add subtask directly to card
  const handleAddInlineSubTask = (taskId: string) => {
    const text = inlineSubTaskText[taskId];
    if (!text || !text.trim()) return;

    const updatedTasks = tasks.map(t => {
      if (t.id !== taskId) return t;

      const newSub: DelegatedTaskSubItem = {
        id: `sub-${Date.now()}`,
        title: text.trim(),
        completed: false
      };

      // If task was complete, switch back to in progress
      const nextStatus = t.status === "Completed" ? "In Progress" : t.status;

      return {
        ...t,
        status: nextStatus,
        subTasks: [...t.subTasks, newSub]
      };
    });

    onUpdateDelegatedTasks(updatedTasks);
    setInlineSubTaskText(prev => ({ ...prev, [taskId]: "" }));
  };

  // Delete Task
  const handleDeleteTask = (taskId: string, title: string) => {
    if (!window.confirm(`Apakah Anda yakin ingin menghapus delegasi tugas "${title}"?`)) return;

    const updatedTasks = tasks.filter(t => t.id !== taskId);
    onUpdateDelegatedTasks(updatedTasks);

    if (onAddAuditLog) {
      onAddAuditLog(employee.id, {
        action: "DELETE",
        category: "Jabatan",
        actorName: currentUser ? currentUser.name : "Manager",
        actorPosition: currentUser ? currentUser.position : "Manager Operasional",
        details: `Penghapusan delegasi tugas "${title}" dari profil pegawai ${employee.name}.`
      });
    }
  };

  return (
    <div className="space-y-6 animate-fadeIn">

      {/* AUTOMATED SUPERVISOR NOTIFICATION ALERT BANNER */}
      {autoNotificationToast && (
        <div className="p-4 bg-emerald-950/90 border-2 border-emerald-400 text-white shadow-2xl flex items-start justify-between gap-4 animate-bounce">
          <div className="flex items-start gap-3">
            <div className="p-2 bg-emerald-500 text-black rounded-none font-bold mt-0.5">
              <Bell className="w-5 h-5 animate-pulse" />
            </div>
            <div className="space-y-1 font-mono">
              <div className="flex items-center gap-2">
                <span className="text-xs font-black uppercase text-emerald-300 tracking-wider">
                  Status Automation Active
                </span>
                <span className="text-[10px] bg-emerald-900 border border-emerald-500 px-2 py-0.5 text-emerald-200">
                  Auto-Notified to Supervisor
                </span>
              </div>
              <p className="text-sm font-bold text-emerald-100">
                Tugas Delegasi &quot;{autoNotificationToast.taskTitle}&quot; 100% SELESAI!
              </p>
              <p className="text-xs text-emerald-300">
                Notifikasi status resmi telah dikirim secara otomatis ke Supervisor: <strong>{autoNotificationToast.supervisorName}</strong> pada {autoNotificationToast.completedAt}.
              </p>
            </div>
          </div>
          <button 
            onClick={() => setAutoNotificationToast(null)}
            className="text-emerald-400 hover:text-white p-1"
          >
            <X className="w-5 h-5" />
          </button>
        </div>
      )}

      {/* DASHBOARD SUMMARY HEADER */}
      <div className="bg-[#0a0a0a] border border-[#222] p-5">
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 pb-4 border-b border-[#1f1f1f]">
          <div>
            <div className="flex items-center gap-2">
              <UserCheck className="w-5 h-5 text-[#facc15]" />
              <h3 className="text-lg font-black text-white uppercase tracking-tight">
                Delegasi Penugasan & Tracking Sub-Tugas
              </h3>
            </div>
            <p className="text-xs text-slate-400 mt-1 font-mono">
              Kelola delegasi pekerjaan dari manajer untuk pegawai <strong>{employee.name}</strong>, lacak checklist sub-tugas, dan kirim update status otomatis ke supervisor.
            </p>
          </div>

          <button
            onClick={handleOpenCreateModal}
            className="bg-[#facc15] hover:bg-yellow-500 text-black font-extrabold uppercase tracking-wider text-xs px-4 py-2.5 rounded-none flex items-center justify-center gap-2 shadow-lg transition-all"
          >
            <Plus className="w-4 h-4 stroke-[3]" />
            Delegasikan Tugas Baru
          </button>
        </div>

        {/* STATS METRIC GRID */}
        <div className="grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4">
          <div className="bg-[#111] border border-[#222] p-3 text-center">
            <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider block font-mono">Total Delegasi</span>
            <span className="text-xl font-black text-white mt-1 block">{stats.total}</span>
          </div>
          <div className="bg-[#111] border border-amber-500/30 p-3 text-center">
            <span className="text-[10px] font-bold text-amber-400 uppercase tracking-wider block font-mono">Menunggu (Pending)</span>
            <span className="text-xl font-black text-amber-300 mt-1 block">{stats.pending}</span>
          </div>
          <div className="bg-[#111] border border-sky-500/30 p-3 text-center">
            <span className="text-[10px] font-bold text-sky-400 uppercase tracking-wider block font-mono">Dalam Proses</span>
            <span className="text-xl font-black text-sky-300 mt-1 block">{stats.inProgress}</span>
          </div>
          <div className="bg-[#111] border border-emerald-500/30 p-3 text-center">
            <span className="text-[10px] font-bold text-emerald-400 uppercase tracking-wider block font-mono">Selesai (Completed)</span>
            <span className="text-xl font-black text-emerald-300 mt-1 block">{stats.completed}</span>
          </div>
          <div className="bg-[#111] border border-indigo-500/30 p-3 text-center col-span-2 sm:col-span-1">
            <span className="text-[10px] font-bold text-indigo-400 uppercase tracking-wider block font-mono">Supervisor Notified</span>
            <span className="text-xl font-black text-indigo-300 mt-1 block flex items-center justify-center gap-1">
              <Send className="w-3.5 h-3.5 text-indigo-400" />
              {stats.notifiedCount}
            </span>
          </div>
        </div>
      </div>

      {/* FILTER & SEARCH BAR */}
      <div className="bg-[#050505] border border-[#222] p-4 flex flex-col md:flex-row gap-3 items-center justify-between">
        {/* Search Input */}
        <div className="relative w-full md:w-72">
          <Search className="w-4 h-4 text-slate-500 absolute left-3 top-3" />
          <input
            type="text"
            placeholder="Cari tugas, deskripsi, manajer..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full bg-[#111] border border-[#222] pl-9 pr-3 py-2 text-xs text-white placeholder-slate-500 focus:outline-hidden focus:border-[#facc15] font-mono"
          />
        </div>

        {/* Dropdown Filters */}
        <div className="flex flex-wrap items-center gap-2 w-full md:w-auto">
          {/* Category / Business Unit Filter */}
          <div className="flex items-center gap-1.5 bg-[#111] border border-[#222] px-2.5 py-1.5 text-xs">
            <Building2 className="w-3.5 h-3.5 text-slate-400" />
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              className="bg-transparent text-slate-200 text-xs font-mono focus:outline-hidden cursor-pointer"
            >
              <option value="ALL" className="bg-black">Semua Unit Bisnis / Client</option>
              {availableCategories.map((cat, idx) => (
                <option key={idx} value={cat} className="bg-black">{cat}</option>
              ))}
            </select>
          </div>

          {/* Priority Filter */}
          <div className="flex items-center gap-1.5 bg-[#111] border border-[#222] px-2.5 py-1.5 text-xs">
            <Filter className="w-3.5 h-3.5 text-slate-400" />
            <select
              value={selectedPriority}
              onChange={(e) => setSelectedPriority(e.target.value)}
              className="bg-transparent text-slate-200 text-xs font-mono focus:outline-hidden cursor-pointer"
            >
              <option value="ALL" className="bg-black">Semua Prioritas</option>
              <option value="High" className="bg-black">Prioritas Tinggi (High)</option>
              <option value="Medium" className="bg-black">Prioritas Sedang (Medium)</option>
              <option value="Low" className="bg-black">Prioritas Rendah (Low)</option>
            </select>
          </div>

          {/* Status Filter */}
          <div className="flex items-center gap-1.5 bg-[#111] border border-[#222] px-2.5 py-1.5 text-xs">
            <CheckSquare className="w-3.5 h-3.5 text-slate-400" />
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="bg-transparent text-slate-200 text-xs font-mono focus:outline-hidden cursor-pointer"
            >
              <option value="ALL" className="bg-black">Semua Status</option>
              <option value="Pending" className="bg-black">Menunggu (Pending)</option>
              <option value="In Progress" className="bg-black">Dalam Proses (In Progress)</option>
              <option value="Completed" className="bg-black">Selesai (Completed)</option>
              <option value="Cancelled" className="bg-black">Dibatalkan</option>
            </select>
          </div>
        </div>
      </div>

      {/* TASK CARDS GRID */}
      {filteredTasks.length === 0 ? (
        <div className="bg-[#050505] border border-[#222] p-12 text-center space-y-3">
          <Layers className="w-12 h-12 text-slate-600 mx-auto" />
          <h4 className="text-sm font-bold text-slate-300 uppercase">Belum Ada Delegasi Tugas Ditemukan</h4>
          <p className="text-xs text-slate-500 max-w-md mx-auto font-mono">
            Tidak ada penugasan yang sesuai dengan filter pencarian. Klik tombol &quot;Delegasikan Tugas Baru&quot; di atas untuk memberikan tugas baru kepada pegawai ini.
          </p>
          <button
            onClick={handleOpenCreateModal}
            className="mt-2 inline-flex items-center gap-2 bg-[#facc15] text-black font-extrabold text-xs px-4 py-2 uppercase tracking-wider"
          >
            <Plus className="w-4 h-4" />
            Buat Penugasan Baru
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
          {filteredTasks.map((task) => {
            const totalSub = task.subTasks.length;
            const completedSub = task.subTasks.filter(s => s.completed).length;
            const progressPercent = totalSub > 0 ? Math.round((completedSub / totalSub) * 100) : 0;
            const isCompleted = task.status === "Completed";
            const isHighPriority = task.priority === "High";

            return (
              <div 
                key={task.id} 
                className={`bg-[#080808] border transition-all relative flex flex-col justify-between ${
                  isCompleted 
                    ? "border-emerald-500/40 bg-emerald-950/10" 
                    : isHighPriority 
                    ? "border-rose-500/40 shadow-sm shadow-rose-950/30" 
                    : "border-[#222] hover:border-slate-600"
                }`}
              >
                {/* CARD HEADER & BADGES */}
                <div className="p-5 space-y-3">
                  <div className="flex items-start justify-between gap-3">
                    <div className="space-y-1">
                      {/* Priority & Category Badges */}
                      <div className="flex flex-wrap items-center gap-2">
                        <span className={`px-2 py-0.5 text-[9px] font-black uppercase tracking-wider border ${
                          task.priority === "High" ? "bg-rose-500/20 text-rose-300 border-rose-500/30" :
                          task.priority === "Medium" ? "bg-amber-500/20 text-amber-300 border-amber-500/30" :
                          "bg-slate-800 text-slate-300 border-slate-700"
                        }`}>
                          Prioritas {task.priority}
                        </span>

                        <span className="px-2 py-0.5 text-[9px] font-bold uppercase tracking-wider bg-slate-900 text-slate-300 border border-slate-800 flex items-center gap-1 font-mono">
                          <Building2 className="w-2.5 h-2.5 text-[#facc15]" />
                          {task.category}
                        </span>
                      </div>

                      {/* Task Title */}
                      <h4 className="text-base font-black text-white leading-snug pt-1">
                        {task.title}
                      </h4>
                    </div>

                    {/* Task Actions Menu */}
                    <div className="flex items-center gap-1 shrink-0">
                      <button
                        onClick={() => handleOpenEditModal(task)}
                        className="p-1.5 text-slate-400 hover:text-white hover:bg-[#1a1a1a] transition-colors"
                        title="Edit Tugas & Sub-Tugas"
                      >
                        <Edit2 className="w-3.5 h-3.5" />
                      </button>
                      <button
                        onClick={() => handleDeleteTask(task.id, task.title)}
                        className="p-1.5 text-rose-400 hover:text-rose-300 hover:bg-rose-950/50 transition-colors"
                        title="Hapus Penugasan"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  </div>

                  {/* Task Description */}
                  {task.description && (
                    <p className="text-xs text-slate-400 leading-relaxed font-mono">
                      {task.description}
                    </p>
                  )}

                  {/* Manager & Supervisor Info */}
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-[11px] font-mono bg-[#111] p-2.5 border border-[#1f1f1f]">
                    <div>
                      <span className="text-slate-500 block text-[9px] uppercase font-bold">Pemberi Tugas (Manager):</span>
                      <span className="text-slate-200 font-semibold">{task.assignedBy}</span>
                    </div>
                    <div>
                      <span className="text-slate-500 block text-[9px] uppercase font-bold">Target Supervisor (Auto-Update):</span>
                      <span className="text-emerald-400 font-semibold flex items-center gap-1">
                        <Send className="w-2.5 h-2.5 text-emerald-400" />
                        {task.supervisorName || "Direct Supervisor"}
                      </span>
                    </div>
                  </div>

                  {/* Progress Bar Component */}
                  <div className="space-y-1 pt-1">
                    <div className="flex items-center justify-between text-[11px] font-mono">
                      <span className="text-slate-400 font-bold flex items-center gap-1.5">
                        <CheckSquare className="w-3.5 h-3.5 text-[#facc15]" />
                        Progres Sub-Tugas: ({completedSub}/{totalSub})
                      </span>
                      <span className={`font-black ${progressPercent === 100 ? "text-emerald-400" : "text-[#facc15]"}`}>
                        {progressPercent}%
                      </span>
                    </div>

                    <div className="w-full bg-[#181818] h-2 rounded-none overflow-hidden border border-[#222]">
                      <div 
                        className={`h-full transition-all duration-500 ${
                          progressPercent === 100 ? "bg-emerald-500" : progressPercent > 50 ? "bg-[#facc15]" : "bg-amber-500"
                        }`}
                        style={{ width: `${progressPercent}%` }}
                      />
                    </div>
                  </div>

                  {/* SUB-TASKS CHECKLIST LISTING */}
                  <div className="space-y-2 pt-2 border-t border-[#1a1a1a]">
                    <div className="text-[10px] uppercase font-bold text-slate-400 tracking-wider">
                      Checklist Sub-Tugas ({totalSub}):
                    </div>

                    <div className="space-y-1.5 max-h-48 overflow-y-auto pr-1">
                      {task.subTasks.map((sub) => (
                        <label
                          key={sub.id}
                          className={`flex items-start gap-2.5 p-2 border transition-all cursor-pointer ${
                            sub.completed 
                              ? "bg-emerald-950/20 border-emerald-800/40 text-emerald-200" 
                              : "bg-[#111] border-[#222] text-slate-300 hover:border-slate-600"
                          }`}
                        >
                          <input
                            type="checkbox"
                            checked={sub.completed}
                            onChange={() => handleToggleSubTask(task.id, sub.id)}
                            className="mt-0.5 accent-[#facc15] w-3.5 h-3.5 rounded-none cursor-pointer"
                          />
                          <span className={`text-xs font-mono leading-tight ${sub.completed ? "line-through text-slate-500" : "text-slate-200"}`}>
                            {sub.title}
                          </span>
                        </label>
                      ))}
                    </div>

                    {/* Quick Add Inline Sub-task */}
                    <div className="flex gap-1.5 pt-1">
                      <input
                        type="text"
                        placeholder="+ Tambah item sub-tugas baru..."
                        value={inlineSubTaskText[task.id] || ""}
                        onChange={(e) => setInlineSubTaskText({ ...inlineSubTaskText, [task.id]: e.target.value })}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter') {
                            e.preventDefault();
                            handleAddInlineSubTask(task.id);
                          }
                        }}
                        className="w-full bg-[#111] border border-[#222] text-xs font-mono text-white px-2.5 py-1.5 placeholder-slate-600 focus:outline-hidden focus:border-[#facc15]"
                      />
                      <button
                        type="button"
                        onClick={() => handleAddInlineSubTask(task.id)}
                        className="bg-[#222] hover:bg-[#333] text-white px-2.5 py-1.5 text-xs font-bold uppercase"
                      >
                        Tambah
                      </button>
                    </div>
                  </div>
                </div>

                {/* CARD FOOTER: STATUS & DUE DATE */}
                <div className="p-3 bg-[#0a0a0a] border-t border-[#1f1f1f] flex flex-col sm:flex-row items-center justify-between gap-3 text-xs font-mono">
                  <div className="flex items-center gap-2">
                    <Calendar className="w-3.5 h-3.5 text-slate-400" />
                    <span className="text-slate-400">Target: <strong className="text-slate-200">{task.dueDate}</strong></span>
                  </div>

                  <div className="flex items-center gap-2 w-full sm:w-auto justify-end">
                    {/* Status Select Dropdown */}
                    <select
                      value={task.status}
                      onChange={(e) => handleStatusChange(task.id, e.target.value as any)}
                      className={`text-xs font-bold uppercase px-2 py-1 border rounded-none cursor-pointer ${
                        task.status === "Completed" ? "bg-emerald-950 text-emerald-300 border-emerald-500" :
                        task.status === "In Progress" ? "bg-sky-950 text-sky-300 border-sky-500" :
                        task.status === "Pending" ? "bg-amber-950 text-amber-300 border-amber-500" :
                        "bg-rose-950 text-rose-300 border-rose-500"
                      }`}
                    >
                      <option value="Pending" className="bg-black text-amber-300">Menunggu (Pending)</option>
                      <option value="In Progress" className="bg-black text-sky-300">Dalam Proses</option>
                      <option value="Completed" className="bg-black text-emerald-300">Selesai (Completed)</option>
                      <option value="Cancelled" className="bg-black text-rose-300">Dibatalkan</option>
                    </select>

                    {/* Supervisor Notification Badge */}
                    {task.supervisorNotified && (
                      <span className="p-1 bg-emerald-500/20 border border-emerald-500 text-emerald-300" title={`Auto-notified to ${task.supervisorName}`}>
                        <Send className="w-3.5 h-3.5" />
                      </span>
                    )}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* MODAL FORM: CREATE / EDIT DELEGATED TASK */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4 animate-fadeIn">
          <div className="bg-[#0a0a0a] border border-[#222] max-w-2xl w-full p-6 text-white space-y-5 shadow-2xl relative max-h-[90vh] overflow-y-auto">
            <div className="flex items-start justify-between border-b border-[#222] pb-3">
              <div>
                <h3 className="text-lg font-black uppercase text-[#facc15] tracking-tight flex items-center gap-2">
                  <UserCheck className="w-5 h-5" />
                  {editingTask ? "Edit Delegasi Penugasan" : "Delegasikan Penugasan Baru"}
                </h3>
                <p className="text-xs text-slate-400 font-mono mt-0.5">
                  Lengkapi detail penugasan, unit bisnis client, prioritas, dan daftar sub-tugas yang perlu diselesaikan pegawai.
                </p>
              </div>

              <button
                type="button"
                onClick={() => setIsModalOpen(false)}
                className="text-slate-400 hover:text-white p-1"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleSaveTaskForm} className="space-y-4">
              {/* Task Title */}
              <div>
                <label className="block text-xs uppercase font-bold text-slate-300 mb-1">
                  Judul Delegasi Tugas: *
                </label>
                <input
                  type="text"
                  required
                  placeholder="Contoh: Audit Sistem PPh 21 & Rekonsiliasi Kas Client PT Synergy"
                  value={taskTitle}
                  onChange={(e) => setTaskTitle(e.target.value)}
                  className="w-full bg-[#111] border border-[#333] text-white p-2.5 text-xs font-mono focus:border-[#facc15] focus:outline-hidden"
                />
              </div>

              {/* Dynamic Business Unit / Category Selection */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs uppercase font-bold text-slate-300 mb-1">
                    Kategori / Unit Bisnis Client: *
                  </label>
                  {!isCustomCategory ? (
                    <select
                      value={taskCategory}
                      onChange={(e) => {
                        if (e.target.value === "CUSTOM") {
                          setIsCustomCategory(true);
                        } else {
                          setTaskCategory(e.target.value);
                        }
                      }}
                      className="w-full bg-[#111] border border-[#333] text-white p-2.5 text-xs font-mono focus:border-[#facc15] focus:outline-hidden"
                    >
                      {DEFAULT_BUSINESS_UNITS.map((unit, idx) => (
                        <option key={idx} value={unit}>{unit}</option>
                      ))}
                      <option value="CUSTOM">+ Tambah Unit Bisnis / Client Custom...</option>
                    </select>
                  ) : (
                    <div className="flex gap-1.5">
                      <input
                        type="text"
                        required
                        placeholder="Ketikkan Nama Unit Bisnis Client..."
                        value={customCategoryInput}
                        onChange={(e) => setCustomCategoryInput(e.target.value)}
                        className="w-full bg-[#111] border border-[#333] text-white p-2.5 text-xs font-mono focus:border-[#facc15]"
                      />
                      <button
                        type="button"
                        onClick={() => setIsCustomCategory(false)}
                        className="bg-[#222] px-3 text-xs text-slate-300 hover:text-white"
                      >
                        Batal
                      </button>
                    </div>
                  )}
                </div>

                {/* Priority Selection */}
                <div>
                  <label className="block text-xs uppercase font-bold text-slate-300 mb-1">
                    Tingkat Prioritas: *
                  </label>
                  <select
                    value={taskPriority}
                    onChange={(e) => setTaskPriority(e.target.value as any)}
                    className="w-full bg-[#111] border border-[#333] text-white p-2.5 text-xs font-mono focus:border-[#facc15] focus:outline-hidden"
                  >
                    <option value="High">Prioritas Tinggi (High)</option>
                    <option value="Medium">Prioritas Sedang (Medium)</option>
                    <option value="Low">Prioritas Rendah (Low)</option>
                  </select>
                </div>
              </div>

              {/* Assigning Manager & Target Supervisor */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs uppercase font-bold text-slate-300 mb-1">
                    Manajer Pemberi Tugas: *
                  </label>
                  <input
                    type="text"
                    required
                    value={taskAssignedBy}
                    onChange={(e) => setTaskAssignedBy(e.target.value)}
                    className="w-full bg-[#111] border border-[#333] text-white p-2.5 text-xs font-mono focus:border-[#facc15]"
                  />
                </div>

                <div>
                  <label className="block text-xs uppercase font-bold text-slate-300 mb-1">
                    Supervisor Penerima Status Update: *
                  </label>
                  <select
                    value={supervisorId}
                    onChange={(e) => setSupervisorId(e.target.value)}
                    className="w-full bg-[#111] border border-[#333] text-white p-2.5 text-xs font-mono focus:border-[#facc15]"
                  >
                    {employees.map((emp) => (
                      <option key={emp.id} value={emp.id}>
                        {emp.name} ({emp.position} — {emp.division})
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* Due Date & Description */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                <div className="md:col-span-1">
                  <label className="block text-xs uppercase font-bold text-slate-300 mb-1">
                    Target Selesai (Due Date): *
                  </label>
                  <input
                    type="date"
                    required
                    value={taskDueDate}
                    onChange={(e) => setTaskDueDate(e.target.value)}
                    className="w-full bg-[#111] border border-[#333] text-white p-2.5 text-xs font-mono focus:border-[#facc15]"
                  />
                </div>

                <div className="md:col-span-2">
                  <label className="block text-xs uppercase font-bold text-slate-300 mb-1">
                    Deskripsi / Rincian Instruksi:
                  </label>
                  <input
                    type="text"
                    placeholder="Contoh: Pastikan seluruh bukti potong PPh 21 diunggah ke DMS sebelum diserahkan"
                    value={taskDescription}
                    onChange={(e) => setTaskDescription(e.target.value)}
                    className="w-full bg-[#111] border border-[#333] text-white p-2.5 text-xs font-mono focus:border-[#facc15]"
                  />
                </div>
              </div>

              {/* SUB-TASKS BUILDER SECTION */}
              <div className="space-y-2 border-t border-[#222] pt-3">
                <label className="block text-xs uppercase font-bold text-[#facc15]">
                  Kelola Daftar Sub-Tugas (Checklist Items):
                </label>

                {/* Subtasks List */}
                <div className="space-y-1.5 max-h-36 overflow-y-auto">
                  {subTasksList.map((item, idx) => (
                    <div key={idx} className="flex items-center justify-between bg-[#111] border border-[#222] p-2 text-xs font-mono">
                      <span className="text-slate-200">{idx + 1}. {item}</span>
                      <button
                        type="button"
                        onClick={() => handleRemoveSubTaskInModal(idx)}
                        className="text-rose-400 hover:text-rose-300 p-1"
                      >
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  ))}
                </div>

                {/* Add Subtask Row */}
                <div className="flex gap-2 pt-1">
                  <input
                    type="text"
                    placeholder="Tambah item sub-tugas baru..."
                    value={newSubTaskInput}
                    onChange={(e) => setNewSubTaskInput(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        handleAddSubTaskInModal();
                      }
                    }}
                    className="w-full bg-[#111] border border-[#333] text-white p-2 text-xs font-mono focus:border-[#facc15]"
                  />
                  <button
                    type="button"
                    onClick={handleAddSubTaskInModal}
                    className="bg-[#222] hover:bg-[#333] text-white px-3 py-2 text-xs font-bold uppercase tracking-wider shrink-0"
                  >
                    + Tambah
                  </button>
                </div>
              </div>

              {/* AUTOMATED SUPERVISOR UPDATE NOTICE */}
              <div className="p-3 bg-emerald-950/40 border border-emerald-500/30 text-emerald-200 text-xs font-mono flex items-start gap-2.5">
                <ShieldCheck className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
                <span>
                  <strong>AUTOMATED SUPERVISOR STATUS UPDATE:</strong> Saat pegawai/manajer menyelesaikan seluruh checklist sub-tugas (100%), notifikasi status otomatis akan langsung dikirimkan ke supervisor terpilih.
                </span>
              </div>

              {/* ACTION BUTTONS */}
              <div className="flex justify-end gap-3 pt-3 border-t border-[#222]">
                <button
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  className="px-4 py-2.5 bg-[#151515] hover:bg-[#222] border border-[#333] text-xs font-bold uppercase tracking-wider text-slate-300"
                >
                  Batal
                </button>
                <button
                  type="submit"
                  className="px-5 py-2.5 bg-[#facc15] hover:bg-yellow-500 text-black font-extrabold uppercase text-xs tracking-wider flex items-center gap-2"
                >
                  <Check className="w-4 h-4 stroke-[3]" />
                  {editingTask ? "Simpan Perubahan Delegasi" : "Terbitkan Delegasi Tugas"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

    </div>
  );
}
