"use client"

import type React from "react"
import { useState } from "react"
import { DataGrid, type GridColDef, type GridRowSelectionModel } from "@mui/x-data-grid"
import { Inertia } from "@inertiajs/inertia"
import { HiOutlinePencilSquare, HiOutlineEye, HiOutlineTrash } from "react-icons/hi2"
import toast from "react-hot-toast"
import { CheckIcon, XMarkIcon as XMarkSolidIcon } from "@heroicons/react/24/solid"

interface DataTableProps {
  columns: GridColDef[]
  rows: object[]
  slug: string
  includeActionColumn: boolean
  viewRoute?: string
  checkboxSelection?: boolean
  onSelectionModelChange?: (newSelection: GridRowSelectionModel) => void
  selectionModel?: GridRowSelectionModel
}

const DataTable: React.FC<DataTableProps> = ({
  columns,
  rows,
  slug,
  includeActionColumn,
  viewRoute,
  checkboxSelection = false,
  onSelectionModelChange,
  selectionModel,
}) => {
  const [hoveredButton, setHoveredButton] = useState<string | null>(null)

  const handleNavigation = (url: string) => {
    Inertia.visit(url)
  }

  const getStatusBadge = (status: string) => {
    const styles = {
      PENDING: "bg-amber-50 text-amber-700 border-amber-200",
      APPROVED: "bg-green-50 text-green-700 border-green-200",
      REJECTED: "bg-red-50 text-red-700 border-red-200",
    }

    const icons = {
      PENDING: <div className="w-2 h-2 rounded-full bg-amber-500 mr-1.5" />,
      APPROVED: <CheckIcon className="w-4 h-4 mr-1.5" />,
      REJECTED: <XMarkSolidIcon className="w-4 h-4 mr-1.5" />,
    }

    const statusLabels: Record<string, string> = {
      PENDING: "En attente",
      APPROVED: "Approuvée",
      REJECTED: "Rejetée",
    }

    return (
      <span
        className={`inline-flex items-center px-3 py-1 text-sm font-medium rounded-full border ${styles[status as keyof typeof styles]}`}
      >
        {icons[status as keyof typeof icons]}
        {statusLabels[status as keyof typeof statusLabels] ?? status}
      </span>
    )
  }

  const getPaymentBadge = (isPaid: boolean | string) => {
    const paid = isPaid === true || isPaid === "true"  || isPaid === "1"

    const styles = paid ? "bg-green-50 text-green-700 border-green-200" : "bg-red-50 text-red-700 border-red-200"

    const icon = paid ? <CheckIcon className="w-4 h-4 mr-1.5" /> : <XMarkSolidIcon className="w-4 h-4 mr-1.5" />

    const label = paid ? "Payé" : "Non payé"

    return (
      <span className={`inline-flex items-center px-3 py-1 text-sm font-medium rounded-full border ${styles}`}>
        {icon}
        {label}
      </span>
    )
  }

  const actionColumn: GridColDef = {
    field: "action",
    headerName: "Actions",
    minWidth: 150,
    flex: 0.7,
    renderCell: (params) => {
      const viewUrl = viewRoute ? `${viewRoute}/${params.row.id}` : `/${slug}/${params.row.id}`

      return (
        <div className="flex items-center gap-3">
          <button
            onClick={() => handleNavigation(viewUrl)}
            onMouseEnter={() => setHoveredButton(`view-${params.row.id}`)}
            onMouseLeave={() => setHoveredButton(null)}
            className="bg-gray-100 hover:bg-gray-800 text-gray-700 hover:text-white p-2 rounded-md transition-all duration-200 shadow-sm"
            title="View"
          >
            <HiOutlineEye
              className={`w-5 h-5 ${hoveredButton === `view-${params.row.id}` ? "scale-110 transition-transform" : ""}`}
            />
          </button>
          <button
            onClick={() => {
              toast("Jangan diedit!", {
                icon: "😠",
              })
            }}
            onMouseEnter={() => setHoveredButton(`edit-${params.row.id}`)}
            onMouseLeave={() => setHoveredButton(null)}
            className="bg-gray-100 hover:bg-gray-800 text-gray-700 hover:text-white p-2 rounded-md transition-all duration-200 shadow-sm"
            title="Edit"
          >
            <HiOutlinePencilSquare
              className={`w-5 h-5 ${hoveredButton === `edit-${params.row.id}` ? "scale-110 transition-transform" : ""}`}
            />
          </button>
          <button
            onClick={() => {
              toast("Jangan dihapus!", {
                icon: "😠",
              })
            }}
            onMouseEnter={() => setHoveredButton(`delete-${params.row.id}`)}
            onMouseLeave={() => setHoveredButton(null)}
            className="bg-gray-100 hover:bg-red-600 text-gray-700 hover:text-white p-2 rounded-md transition-all duration-200 shadow-sm"
            title="Delete"
          >
            <HiOutlineTrash
              className={`w-5 h-5 ${hoveredButton === `delete-${params.row.id}` ? "scale-110 transition-transform" : ""}`}
            />
          </button>
        </div>
      )
    },
  }

  const customStyles = {}

  const processedColumns = columns.map((column) => {
    // Check if this is a status column
    if (column.field === "status") {
      return {
        ...column,
        flex: column.flex || 1,
        minWidth: column.minWidth || 100,
        renderCell: (params: { value: string }) => getStatusBadge(params.value as string),
      }
    }

    if (column.field === "Paiement") {
      return {
        ...column,
        flex: column.flex || 1,
        minWidth: column.minWidth || 120,
        renderCell: (params: any) => getPaymentBadge(params.row.is_transaction_paid),
      }
    }

    // Custom rendering for user column: show name, then email below in smaller font
    if (column.field === "user") {
      return {
        ...column,
        flex: column.flex || 1,
        minWidth: column.minWidth || 140,
        renderCell: (params: any) => (
          <div className="flex flex-col">
            <span className="font-medium text-gray-900 text-sm">{params.row.user?.name ?? ""}</span>
            {params.row.user?.email && <span className="text-xs text-gray-500 mt-1">{params.row.user.email}</span>}
          </div>
        ),
      }
    }
    return {
      ...column,
      flex: column.flex || 1,
      minWidth: column.minWidth || 100,
      renderCell:
        column.renderCell ||
        ((params) => <div className="whitespace-normal break-words">{params.value as string}</div>),
    }
  })

  const tableContent = (
    <DataGrid
      sx={customStyles}
      className="dataGrid p-0 xl:p-3 w-full bg-white text-gray-800 shadow-sm"
      rows={rows || []}
      columns={
        includeActionColumn
          ? ([...processedColumns, actionColumn] as GridColDef[])
          : ([...processedColumns] as GridColDef[])
      }
      getRowHeight={() => "auto"}
      getRowClassName={(params) => (params.row.user?.is_favorite ? "bg-yellow-50" : "")}
      initialState={{
        pagination: {
          paginationModel: {
            pageSize: 10,
          },
        },
        columns: {
          columnVisibilityModel: {
            created_at: window.innerWidth > 768,
          },
        },
      }}
      pageSizeOptions={[5, 10, 25]}
      disableRowSelectionOnClick
      disableColumnFilter
      disableDensitySelector
      disableColumnSelector
      autoHeight
      checkboxSelection={checkboxSelection}
      onRowSelectionModelChange={onSelectionModelChange}
      rowSelectionModel={selectionModel}
    />
  )

  return (
    <div className="w-full flex flex-col">
      <div className="bg-white rounded-xl shadow-md overflow-hidden border border-gray-200">{tableContent}</div>
    </div>
  )
}

export default DataTable
