'use client';

import { useState } from 'react';
import { routes } from '@/config/routes';
import { useDrawer } from '@/components/common/Drawer';
import TableLayout from '../../table-layout';
import {
  PiPlusBold,
  PiListBullets,
  PiPulse,
  PiPen,
  PiBuilding,
  PiUserCircle,
  PiCalendarBlank,
  PiCopySimple,
  PiWarningCircle,
  PiCheckCircle,
  PiArrowCounterClockwise,
  PiDotsThreeVertical,
  PiBell,
  PiPaperPlaneTilt,
  PiStack,
  PiMapPin,
  PiCheckSquare,
} from 'react-icons/pi';
import ViewToggle from '@/components/common/ViewToggle';

// ── Types ──────────────────────────────────────────────────────────────
type TaskStatus = 'Completed' | 'In Progress' | 'Not Started' | 'Blocked';
type TaskCategory = 'Foundation' | 'Structure' | 'MEP & Finishing' | 'Pre-Construction';

interface ActivityEntry {
  id: number;
  user: string;
  time: string;
  message: string;
  type: 'comment' | 'status' | 'blocker';
}

interface Subtask {
  title: string;
  completed: boolean;
}

interface Task {
  id: number;
  category: TaskCategory;
  title: string;
  contractor: string;
  date: string;
  subtasks: Subtask[];
  totalSubtasks: number;
  status: TaskStatus;
  hasWarning?: boolean;
  description?: string;
  activity: ActivityEntry[];
}

// ── Static Data ────────────────────────────────────────────────────────

const task = {
  subtasks: 1,
  totalSubtasks: 2,
  subtaskList: [
    {
      title: "Formwork",
      completed: true,
    },
    {
      title: "Pouring",
      completed: false,
    },
  ],
};
const INITIAL_TASKS: Task[] = [
  {
    id: 1,
    category: 'Foundation',
    title: 'Excavation for Wing A',
    contractor: 'L&T Construction',
    date: '2023-08-15',
    subtasks: [
      {
        title: "Formwork",
        completed: true,
      },
      {
        title: "Pouring",
        completed: false,
      },
    ],
    totalSubtasks: 0,
    status: 'Completed',
    activity: [
      { id: 3, user: 'Current User', time: '25/05/2026, 17:30:15', message: 'Changed status to Completed', type: 'status' },
      { id: 2, user: 'Current User', time: '25/05/2026, 17:30:08', message: 'Changed status to In Progress', type: 'status' },
      { id: 1, user: 'Current User', time: '25/05/2026, 17:30:03', message: 'Flagged Blocker: General Issue', type: 'blocker' },
    ],
  },
  {
    id: 2,
    category: 'Foundation',
    title: 'Plinth Beam Casting',
    contractor: 'L&T Construction',
    date: '2023-09-05',
     subtasks: [
      {
        title: 'Rebar Setup',
        completed: true,
      },
      {
        title: 'Concrete Pour',
        completed: false,
      },
    ],
    totalSubtasks: 2,
    status: 'In Progress',
    hasWarning: true,
    activity: [],
  },
  {
    id: 3,
    category: 'Structure',
    title: '1st Floor Slab',
    contractor: 'Shapoorji Pallonji',
    date: '2023-09-25',
    subtasks: [
      
    ],
    totalSubtasks: 0,
    status: 'Not Started',
    activity: [],
  },
  {
    id: 4,
    category: 'Structure',
    title: 'Brickwork Ground Floor',
    contractor: 'L&T Construction',
    date: '2023-09-10',
    subtasks: [
      
    ],
    totalSubtasks: 0,
    status: 'Blocked',
    activity: [],
  },
];

// ── Config ─────────────────────────────────────────────────────────────
const STATUS_STYLES: Record<TaskStatus, string> = {
  'Completed':   'bg-emerald-100 text-emerald-700',
  'In Progress': 'bg-blue-100 text-blue-700',
  'Not Started': 'bg-gray-100 text-gray-600',
  'Blocked':     'bg-red-100 text-red-600',
};

const LEFT_BORDER: Record<TaskStatus, string> = {
  'Completed':   'border-l-4 border-l-emerald-400',
  'In Progress': 'border-l-4 border-l-blue-400',
  'Not Started': 'border-l-4 border-l-gray-300',
  'Blocked':     'border-l-4 border-l-red-400',
};

const CATEGORY_STYLES: Record<TaskCategory, string> = {
  'Foundation':      'text-indigo-600',
  'Structure':       'text-orange-600',
  'MEP & Finishing': 'text-teal-600',
  'Pre-Construction':'text-purple-600',
};

const FILTER_TABS = ['All', 'Pre-Construction', 'Structure', 'MEP & Finishing'] as const;
type FilterTab = typeof FILTER_TABS[number];

const HOVER_LEFT_BORDER: Record<TaskStatus, string> = {
  'Completed':   'hover:border-l-4 hover:border-l-emerald-400',
  'In Progress': 'hover:border-l-4 hover:border-l-blue-400',
  'Not Started': 'hover:border-l-4 hover:border-l-gray-300',
  'Blocked':     'hover:border-l-4 hover:border-l-red-400',
};

const pageHeader = {
  title: 'Task Planner',
  breadcrumb: [
    { href: routes.dashboard, name: 'Home' },
    { name: 'Property Management' },
  ],
};

// ── Task Card ──────────────────────────────────────────────────────────
function TaskCard({
  task,
  selected,
  onClick,
}: {
  task: Task;
  selected: boolean;
  onClick: () => void;
}) {
  return (
    <div
      onClick={onClick}
      className={`cursor-pointer rounded-lg border bg-white px-4 py-3 transition hover:shadow-sm
        ${selected 
          ? `border border-primary border-2 shadow-sm` 
          : 'border-gray-200'}
        ${HOVER_LEFT_BORDER[task.status]}
      `}
    >
      <div className="flex items-start justify-between mb-1.5">
        <div className="flex items-center gap-1.5">
          <span className={`text-xs font-black uppercase tracking-widest ${CATEGORY_STYLES[task.category]}`}>
            {task.category}
          </span>
          {task.hasWarning && (
            <PiWarningCircle size={13} className="text-orange-400" />
          )}
        </div>
        <span className={`text-xs font-bold uppercase tracking-wider px-2.5 py-0.5 rounded-full ${STATUS_STYLES[task.status]}`}>
          {task.status}
        </span>
      </div>
      <p className="text-sm font-bold text-gray-900 mb-2">{task.title}</p>
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <span className="flex items-center gap-1 text-xs text-gray-400">
            <PiUserCircle size={13} />
            {task.contractor}
          </span>
          <span className="flex items-center gap-1 text-xs text-gray-400">
            <PiCalendarBlank size={13} />
            {task.date}
          </span>
        </div>
        <span className="flex items-center gap-1 text-xs text-gray-400">
          <PiCheckSquare size={13} />
          {task.subtasks.filter(st => st.completed).length}/{task.totalSubtasks}
        </span>
      </div>
    </div>
  );
}

// ── Detail Panel ───────────────────────────────────────────────────────
function DetailPanel({
  task,
  onStatusChange,
}: {
  task: Task;
  onStatusChange: (id: number, status: TaskStatus, activityMsg: string, type: ActivityEntry['type']) => void;
}) {
  const [comment, setComment] = useState('');
  const [activities, setActivities] = useState<ActivityEntry[]>(task.activity);

  // sync when task changes
  useState(() => { setActivities(task.activity); });

  const isBlocked = task.status === 'Blocked';
  const isCompleted = task.status === 'Completed';

  const addActivity = (msg: string, type: ActivityEntry['type']) => {
    const now = new Date();
    const timeStr = now.toLocaleString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(',', ',');
    const entry: ActivityEntry = { id: Date.now(), user: 'Current User', time: timeStr, type, message: msg };
    setActivities(prev => [entry, ...prev]);
    onStatusChange(task.id, task.status, msg, type);
  };

  const handleMarkDone = () => {
    onStatusChange(task.id, 'Completed', 'Changed status to Completed', 'status');
    addActivity('Changed status to Completed', 'status');
  };

  const handleResumeWork = () => {
    onStatusChange(task.id, 'In Progress', 'Changed status to In Progress', 'status');
    addActivity('Changed status to In Progress', 'status');
  };

  const handleReportBlocker = () => {
    onStatusChange(task.id, 'Blocked', 'Flagged Blocker: General Issue', 'blocker');
    addActivity('Flagged Blocker: General Issue', 'blocker');
  };

  const handleSendComment = () => {
    if (!comment.trim()) return;
    addActivity(comment.trim(), 'comment');
    setComment('');
  };

  return (
    <div className="flex flex-col h-full bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
      {/* Header */}
      <div className="px-5 pt-5 pb-3 border-b border-gray-100">
        <div className="flex items-start justify-between">
          <div>
            <h2 className="text-base font-bold text-gray-900">{task.title}</h2>
            <p className="flex items-center gap-1 text-xs text-gray-400 mt-0.5">
              <PiMapPin size={12} /> Wing A
            </p>
          </div>
          <div className="flex items-center gap-2">
            {/* <button className="w-7 h-7 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:bg-gray-50">
              <PiBell size={14} />
            </button>
            <button className="w-7 h-7 rounded-lg border border-gray-200 flex items-center justify-center text-gray-400 hover:bg-gray-50">
              <PiDotsThreeVertical size={14} />
            </button> */}
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex gap-2 mt-3">
          {isCompleted ? (
            <button
              onClick={handleReportBlocker}
              className="flex-1 flex items-center justify-center gap-2 bg-red-50 border border-red-200 text-red-600 text-xs font-bold py-2 rounded-lg hover:bg-red-100 transition"
            >
              <PiWarningCircle size={14} /> Report Blocker
            </button>
          ) : isBlocked ? (
            <>
              <button
                onClick={handleMarkDone}
                className="flex-1 flex items-center justify-center gap-2 bg-emerald-500 text-white text-xs font-bold py-2 rounded-lg hover:bg-emerald-600 transition"
              >
                <PiCheckCircle size={14} /> Mark Done
              </button>
              <button
                onClick={handleResumeWork}
                className="flex-1 flex items-center justify-center gap-2 bg-primary text-white text-xs font-bold py-2 rounded-lg hover:opacity-90 transition"
              >
                <PiArrowCounterClockwise size={14} /> Resume Work
              </button>
            </>
          ) : (
            <>
              <button
                onClick={handleMarkDone}
                className="flex-1 flex items-center justify-center gap-2 bg-emerald-500 text-white text-xs font-bold py-2 rounded-lg hover:bg-emerald-600 transition"
              >
                <PiCheckCircle size={14} /> Mark Done
              </button>
              <button
                onClick={handleReportBlocker}
                className="flex-1 flex items-center justify-center gap-2 bg-red-50 border border-red-200 text-red-600 text-xs font-bold py-2 rounded-lg hover:bg-red-100 transition"
              >
                <PiWarningCircle size={14} /> Report Blocker
              </button>
            </>
          )}
        </div>
      </div>

      {/* Scrollable body */}
      <div className="flex-1 overflow-y-auto px-5 py-4 space-y-5">

        {/* Active Blocker Banner */}
        {isBlocked && (
          <div className="bg-red-50 border border-red-200 rounded-lg px-4 py-3">
            <p className="text-xs font-bold text-red-600 uppercase tracking-wider mb-1 flex items-center gap-1">
              <PiWarningCircle size={13} /> Active Blocker
            </p>
            <p className="text-xs text-red-500">• General Issue: Manual Blocker Logged</p>
          </div>
        )}

        {/* Description */}
        <div>
          <p className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-2">Description</p>
          <div className="min-h-[36px] border border-gray-100 rounded-lg bg-gray-50 px-3 py-2 text-xs text-gray-400 italic">
            {task.description || ''}
          </div>
        </div>

        {/* Subtasks */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <p className="text-[11px] font-bold uppercase tracking-[0.2em] text-gray-400">
              Subtasks
            </p>

            <span className="text-[11px] text-gray-400">
              {task.subtasks.filter(st => st.completed).length}/{task.totalSubtasks}
            </span>
          </div>

          {task.totalSubtasks > 0 ? (
            <div className="space-y-2">
              {task.subtasks.map((subtask, index) => (
                <label
                  key={index}
                  className="flex items-center gap-2 text-sm text-gray-700 cursor-pointer"
                >
                  <input
                    type="checkbox"
                    checked={subtask.completed}
                    readOnly
                    className="h-4 w-4 rounded border-gray-300 text-purple-600 focus:ring-purple-500"
                  />

                  <span
                    className={
                      subtask.completed
                        ? "line-through text-gray-400"
                        : "text-gray-700"
                    }
                  >
                    {subtask.title}
                  </span>
                </label>
              ))}
            </div>
          ) : (
            <p className="text-xs text-gray-300 italic">
              No subtasks defined.
            </p>
          )}
        </div>

        {/* Activity Stream */}
        <div>
          <p className="text-xs font-bold uppercase tracking-widest text-gray-400 mb-3 flex items-center gap-1.5">
            <PiPulse size={12} /> Activity Stream
          </p>

          {/* Comment input */}
          <div className="flex items-center gap-2 mb-4">
            <div className="w-2 h-2 rounded-full bg-gray-300 flex-shrink-0" />
            <div className="flex-1 flex items-center gap-2 border border-gray-200 rounded-lg px-3 py-2 bg-white">
              <input
                type="text"
                placeholder="Write a comment..."
                value={comment}
                onChange={e => setComment(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && handleSendComment()}
                className="flex-1 text-xs text-gray-600 outline-none placeholder-gray-300"
              />
              <button
                onClick={handleSendComment}
                className="w-7 h-7 rounded-lg bg-primary flex items-center justify-center flex-shrink-0 hover:opacity-90 transition"
              >
                <PiPaperPlaneTilt size={13} className="text-white" />
              </button>
            </div>
          </div>

          {/* Activity entries */}
          <div className="space-y-3">
            {activities.map(entry => (
              <div key={entry.id} className="flex items-start gap-2.5">
                <div className={`w-2 h-2 rounded-full mt-1.5 flex-shrink-0 ${
                  entry.type === 'blocker' ? 'bg-red-500' :
                  entry.type === 'status'  ? 'bg-blue-500' : 'bg-gray-300'
                }`} />
                <div className="flex-1">
                  <div className="flex items-center justify-between mb-0.5">
                    <span className="text-xs font-semibold text-gray-700">{entry.user}</span>
                    <span className="text-xs text-gray-400">{entry.time}</span>
                  </div>
                  {entry.type === 'blocker' ? (
                    <div className="bg-red-50 border border-red-100 rounded-lg px-3 py-2">
                      <p className="text-xs text-red-600 font-medium">{entry.message}</p>
                    </div>
                  ) : (
                    <p className="text-xs text-gray-500">{entry.message}</p>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Empty Detail Panel ─────────────────────────────────────────────────
function EmptyDetailPanel() {
  return (
    <div className="flex flex-col items-center justify-center h-full bg-white rounded-xl border border-gray-200 shadow-sm text-gray-300">
      <PiStack size={40} className="mb-3" />
      <p className="text-sm font-medium text-gray-400">Select a task to view details &amp; timeline</p>
    </div>
  );
}

// ── Main Page ──────────────────────────────────────────────────────────
export default function Page() {
  const { openDrawer } = useDrawer();
  const [tasks, setTasks] = useState<Task[]>(INITIAL_TASKS);
  const [selectedTaskId, setSelectedTaskId] = useState<number | null>(null);
  const [activeFilter, setActiveFilter] = useState<FilterTab>('All');

  const selectedTask = tasks.find(t => t.id === selectedTaskId) ?? null;

  const filteredTasks = tasks.filter(t => {
    if (activeFilter === 'All') return true;
    if (activeFilter === 'Structure') return t.category === 'Structure';
    if (activeFilter === 'Pre-Construction') return t.category === 'Pre-Construction';
    if (activeFilter === 'MEP & Finishing') return t.category === 'MEP & Finishing';
    return true;
  });

  const handleStatusChange = (
    id: number,
    status: TaskStatus,
    msg: string,
    type: ActivityEntry['type']
  ) => {
    setTasks(prev =>
      prev.map(t => {
        if (t.id !== id) return t;
        const newEntry: ActivityEntry = {
          id: Date.now(),
          user: 'Current User',
          time: new Date().toLocaleString('en-GB'),
          message: msg,
          type,
        };
        return {
          ...t,
          status: type === 'status'
            ? (msg.includes('Completed') ? 'Completed' : msg.includes('In Progress') ? 'In Progress' : t.status)
            : type === 'blocker' ? 'Blocked' : t.status,
          activity: [newEntry, ...t.activity],
        };
      })
    );
  };

  return (
    <TableLayout
      title={pageHeader.title}
      breadcrumb={pageHeader.breadcrumb}
      data={[]}
      fileName="task_planner"
      header="Module,Add,Edit,Delete,View"
      showExport={false}
      showImport={false}
      actions={
        <div className="flex items-center gap-2 justify-end">
          <button
            className="flex items-center gap-2 bg-primary text-white text-sm font-semibold px-4 py-2 rounded-lg shadow hover:opacity-90 transition"
          >
            <PiPlusBold size={15} />
            Add New Task
          </button>
          <ViewToggle
            views={[
              { label: 'Overview',      path: '/project_overview',     icon: PiPulse       },
              { label: 'Task Planner',  path: '/task_planner',         icon: PiListBullets },
              { label: 'Modifications', path: '/project_modification', icon: PiPen         },
              { label: 'Projects',      path: '/manage_project',       icon: PiBuilding    },
            ]}
          />
        </div>
      }
    >
      <div className="flex gap-4 min-h-[calc(100vh-200px)]">
        <div className="w-[520px] flex-shrink-0 bg-white border border-gray-200 rounded-lg shadow-sm flex flex-col">

          {/* Filter tabs */}
          <div className="flex items-center gap-2 px-5 py-3 border-b border-gray-100 flex-wrap">
            {FILTER_TABS.map(tab => (
              <button
                key={tab}
                onClick={() => setActiveFilter(tab)}
                className={`text-xs font-semibold px-3 py-1.5 rounded-full transition ${
                  activeFilter === tab
                    ? 'bg-gray-900 text-white'
                    : 'bg-white border border-gray-200 text-gray-600 hover:border-gray-300'
                }`}
              >
                {tab}
              </button>
            ))}
          </div>

          {/* Task list */}
          <div className="flex-1 overflow-y-auto px-5 py-4 space-y-3">
            {filteredTasks.map(task => (
              <TaskCard
                key={task.id}
                task={task}
                selected={selectedTaskId === task.id}
                onClick={() => setSelectedTaskId(task.id)}
              />
            ))}
          </div>
        </div>
        <div className="flex-1 min-w-0">
          {selectedTask
            ? <DetailPanel task={selectedTask} onStatusChange={handleStatusChange} />
            : <EmptyDetailPanel />
          }
        </div>
      </div>
    </TableLayout>
  );
}