import React, { useState, useMemo } from "react";
import DataTable from "react-data-table-component";
import { Filter } from "lucide-react";
import { initialCasesSeed } from "@/constant/data";

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

const InlineFilterComponent = ({ filters, setFilters, onClear }) => {
  return (
    <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>
        </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 Dashboard = () => {
  const [data] = useState(initialCasesSeed);
  const [filters, setFilters] = useState({
    searchText: "",
    category: "",
    priority: "",
    status: "",
  });
  const [showFilters, setShowFilters] = useState(false);

  // Filter logic
  const filteredData = useMemo(
    () =>
      data.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;
      }),
    [data, filters]
  );

  // Summary counts
  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;
    return { total, pending, approved, scheduled };
  }, [filteredData]);

  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: "Requested Date", selector: (row) => row.requested, 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>
      ),
    },
    {
      name: "Status",
      selector: (row) => row.status,
      sortable: true,
      width: "140px",
      cell: (row) => {
        let bg = "bg-gray-100 text-gray-800";
        if (row.status === "Pending") bg = "bg-yellow-100 text-yellow-800";
        else if (row.status === "Approved") bg = "bg-green-100 text-green-800";
        else if (row.status === "Rejected") bg = "bg-red-100 text-red-800";
        else if (row.status === "Scheduled") bg = "bg-blue-100 text-blue-800";
        return (
          <span className={`px-2 py-1 rounded-full text-xs font-medium ${bg}`}>
            {row.status}
          </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="w-full bg-white rounded-lg shadow-md p-6 mb-4">
      <h2 className="text-lg font-semibold text-gray-700 mb-4">File Upload</h2>

      <label
        htmlFor="ocrFile"
        className="flex flex-col items-center justify-center w-full h-40 border-2 border-dashed border-gray-300 rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100 transition"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          className="w-10 h-10 text-gray-400 mb-2"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth="1.5"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-9 0V3m0 13.5l-3.75-3.75M12 16.5l3.75-3.75"
          />
        </svg>

        <p className="text-sm text-gray-500">
          <span className="font-medium text-blue-600 hover:underline">Click to upload</span> or drag & drop
        </p>
        <p className="text-xs text-gray-400 mt-1">PNG, JPG, or PDF (max 10MB)</p>
        <input id="ocrFile" type="file" className="hidden" accept=".png,.jpg,.jpeg,.pdf" />
      </label>

      <button
        type="button"
        className="mt-4 w-full bg-blue-800 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-lg transition"
      >
        Submit
      </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">Case List</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>

        {/* Summary Section */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
          <div className="bg-gray-100 p-3 rounded-lg text-center">
            <div className="text-sm text-gray-500">Total Cases</div>
            <div className="text-lg font-semibold text-gray-800">{summary.total}</div>
          </div>
          <div className="bg-yellow-100 p-3 rounded-lg text-center">
            <div className="text-sm text-yellow-800">Pending</div>
            <div className="text-lg font-semibold text-yellow-900">{summary.pending}</div>
          </div>
          <div className="bg-green-100 p-3 rounded-lg text-center">
            <div className="text-sm text-green-800">Approved</div>
            <div className="text-lg font-semibold text-green-900">{summary.approved}</div>
          </div>
          <div className="bg-blue-100 p-3 rounded-lg text-center">
            <div className="text-sm text-blue-800">Scheduled</div>
            <div className="text-lg font-semibold text-blue-900">{summary.scheduled}</div>
          </div>
        </div>

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

        {/* DataTable */}
        <DataTable
          columns={columns}
          data={filteredData}
          pagination
          highlightOnHover
          striped
          customStyles={customStyles}
          noDataComponent={
            <div className="py-6 text-gray-500">No matching cases found</div>
          }
        />
      </div>
    </div>
  );
};

export default Dashboard;
