import React, { useState, useMemo } from "react";
import DataTable from "react-data-table-component";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import { Filter, Calendar } from "lucide-react";
import { initialCasesSeed } from "@/constant/data"; // ✅ import your seed file
import { useNavigate } from "react-router-dom";

// 🎨 Priority color mapping
const priorityColorMap = {
  High: "bg-red-100 text-red-800",
  Medium: "bg-yellow-100 text-yellow-800",
  Low: "bg-green-100 text-green-800",
};

const categoryList = ["All", "TH", "TL", "FLSS", "LM", "TP"];

// 🎯 Inline Filter Component
const InlineFilterComponent = ({ filters, setFilters, onClear }) => (
  <div className="p-4 bg-gray-50 border rounded-lg mb-4 grid grid-cols-1 md:grid-cols-4 gap-4">
    {/* Search */}
    <div>
      <label className="text-sm font-medium text-gray-600">Search</label>
      <input
        type="text"
        placeholder="Search by name or ID"
        className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        value={filters.searchText}
        onChange={(e) =>
          setFilters((prev) => ({ ...prev, searchText: e.target.value }))
        }
      />
    </div>

    {/* Category */}
    <div>
      <label className="text-sm font-medium text-gray-600">Category</label>
      <select
        className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        value={filters.category}
        onChange={(e) =>
          setFilters((prev) => ({ ...prev, category: e.target.value }))
        }
      >
        <option value="">All</option>
        <option value="FLSS">FLSS</option>
        <option value="TH">TH</option>
        <option value="TP">TP</option>
        <option value="LM">LM</option>
        <option value="TL">TL</option>
      </select>
    </div>

    {/* Priority */}
    <div>
      <label className="text-sm font-medium text-gray-600">Priority</label>
      <select
        className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        value={filters.priority}
        onChange={(e) =>
          setFilters((prev) => ({ ...prev, priority: e.target.value }))
        }
      >
        <option value="">All</option>
        <option value="High">High</option>
        <option value="Medium">Medium</option>
        <option value="Low">Low</option>
      </select>
    </div>

    {/* Status */}
    <div>
      <label className="text-sm font-medium text-gray-600">Status</label>
      <select
        className="w-full border border-gray-300 rounded-md px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
        value={filters.status}
        onChange={(e) =>
          setFilters((prev) => ({ ...prev, status: e.target.value }))
        }
      >
        <option value="">All</option>
        <option value="Pending">Pending</option>
        <option value="Approved">Approved</option>
        <option value="Rejected">Rejected</option>
        <option value="Scheduled">Scheduled</option>
      </select>
    </div>

    {/* Clear */}
    <div className="col-span-full flex justify-end">
      <button
        onClick={onClear}
        className="bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-1.5 rounded-md text-sm font-medium"
      >
        Clear Filters
      </button>
    </div>
  </div>
);

const Taskboard = () => {
  const navigate = useNavigate();
  const [data] = useState(initialCasesSeed);
  const [filters, setFilters] = useState({
    searchText: "",
    category: "",
    priority: "",
    status: "",
  });
  const [showFilters, setShowFilters] = useState(false);
  const [category, setCategoory] = useState("All");

  const today = new Date().toISOString().split("T")[0]; // e.g. "2025-11-03"

  // 🧠 Only tasks scheduled for today
  const todayScheduled = useMemo(() => {
    return data.filter(
      (item) => item.scheduled && item.scheduled.startsWith(today)
    );
  }, [data, today]);

  // 🧠 Apply filters
  const filteredData = useMemo(() => {
    return todayScheduled.filter((item) => {
      const matchSearch =
        item.name.toLowerCase().includes(filters.searchText.toLowerCase()) ||
        item.id.toLowerCase().includes(filters.searchText.toLowerCase());
      const matchCategory =
        filters.category === "" || item.category === filters.category;
      const matchPriority =
        filters.priority === "" || item.priority === filters.priority;
      const matchStatus =
        filters.status === "" || item.status === filters.status;
      return matchSearch && matchCategory && matchPriority && matchStatus;
    });
  }, [todayScheduled, filters]);

  // 📊 Summary
  const summary = useMemo(() => {
    const total = filteredData.length;
    const pending = filteredData.filter((x) => x.status === "Pending").length;
    const approved = filteredData.filter((x) => x.status === "Approved").length;
    const scheduled = filteredData.filter((x) => x.status === "Scheduled").length;
    const rejected = filteredData.filter((x) => x.status === "Rejected").length;
    return { total, pending, approved, scheduled, rejected };
  }, [filteredData]);

  // 🗓️ Calendar events (color by priority)
  const calendarEvents = filteredData.map((task) => {
    const start = new Date(task.scheduled);
    const end = new Date(start.getTime() + 2 * 60 * 60 * 1000); // +2 hours

    // 🎨 Priority color map for calendar
    const priorityColor =
        task.priority === "High"
        ? "#ef4444" // red
        : task.priority === "Medium"
        ? "#f97316" // orange
        : "#3b82f6"; // green (low)

    return {
        id: task.id,
        title: `${task.id} - ${task.name}`,
        start,
        end,
        color: priorityColor,
    };
  });

  // 📋 DataTable
  const columns = [
    { name: "Case ID", selector: (row) => row.id, sortable: true, width: "120px" },
    { name: "Category", selector: (row) => row.category, sortable: true, width: "120px" },
    { name: "Name", selector: (row) => row.name, sortable: true, wrap: true },
    {
        name: "Scheduled Time",
        selector: (row) => {
            if (!row.scheduled) return "-";
            const dateObj = new Date(row.scheduled);
            const date = dateObj.toLocaleDateString("en-GB", {
            year: "numeric",
            month: "short",
            day: "2-digit",
            });
            const time = dateObj.toLocaleTimeString("en-US", {
            hour: "numeric",
            minute: "2-digit",
            hour12: true,
            });
            return `${time}`;
    },
    sortable: true,
    width: "200px",
    },
    {
      name: "Priority",
      selector: (row) => row.priority,
      sortable: true,
      width: "120px",
      cell: (row) => (
        <span
          className={`px-2 py-1 rounded-full text-xs font-medium ${priorityColorMap[row.priority]}`}
        >
          {row.priority}
        </span>
      ),
    },
  ];

  const customStyles = {
    headRow: {
      style: {
        backgroundColor: "#1A237E",
        color: "#ffffff",
        fontSize: "14px",
        fontWeight: "600",
      },
    },
    rows: {
      style: {
        fontSize: "14px",
        "&:nth-of-type(odd)": { backgroundColor: "#f9fafb" },
      },
    },
  };

  return (
    <div>
      <div className="py-4 grid grid-cols-6 gap-3">
        {categoryList.map((cat) => (
          <button
            key={cat}
            onClick={() =>
              navigate(`/taskboards/${cat === "All" ? "all" : cat.toLowerCase()}`)
            }
            className={`text-center px-4 py-2 rounded-lg border font-medium text-sm transition
              ${
                category === cat
                  ? "bg-blue-600 text-white border-blue-600"
                  : "bg-white text-gray-700 hover:bg-blue-50 hover:text-blue-600"
              }`}
          >
            {cat}
          </button>
        ))}
      </div>

      <div className="w-full bg-white rounded-lg shadow-md p-6">
        {/* Header */}
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-xl font-semibold text-gray-800">
            Scheduled Cases for Today ({today})
          </h2>
          <button
            onClick={() => setShowFilters(!showFilters)}
            className="flex items-center gap-2 bg-blue-600 text-white px-3 py-1.5 rounded-md hover:bg-blue-700 text-sm"
          >
            <Filter size={16} />
            Filter
          </button>
        </div>

        {/* Filter */}
        {showFilters && (
          <InlineFilterComponent
            filters={filters}
            setFilters={setFilters}
            onClear={() =>
              setFilters({
                searchText: "",
                category: "",
                priority: "",
                status: "",
              })
            }
          />
        )}

        {/* Table */}
        <DataTable
          columns={columns}
          data={filteredData}
          pagination
          highlightOnHover
          striped
          customStyles={customStyles}
          noDataComponent={
            <div className="py-6 text-gray-500">No scheduled tasks for today</div>
          }
        />

        {/* Calendar */}
        <div className="mt-6 border rounded-lg shadow-sm p-4 bg-gray-50">
          <div className="flex items-center mb-3 gap-2 text-gray-700">
            <Calendar size={18} />
            <h3 className="text-lg font-semibold">Today's Schedule</h3>
          </div>

          <FullCalendar
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            initialView="timeGridDay"
            initialDate={today}
            slotMinTime="07:00:00"
            slotMaxTime="20:00:00"
            height="auto"
            nowIndicator={true}
            headerToolbar={{
              left: "title",
              right: "timeGridDay",
            }}
            events={calendarEvents}
            eventDisplay="block"
            eventTimeFormat={{
              hour: "2-digit",
              minute: "2-digit",
              hour12: true,
            }}
          />
        </div>
      </div>
    </div>
  );
};

export default Taskboard;
