"use client"

import { useState } from "react"
import Link from "next/link"
import { bulkDeleteEntriesAction, bulkApproveEntriesAction } from "@/app/admin/actions"
import { useRouter } from "next/navigation"

type Entry = {
  id: string
  title: string
  subjectName: string
  city: string
  county: string
  status: string
  stage: number
  createdAt: Date | string
  user: {
    name: string | null
    email: string | null
    class: string | null
  }
}

export function BulkEntryActions({ entries }: { entries: Entry[] }) {
  const router = useRouter()
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [isDeleting, setIsDeleting] = useState(false)
  const [isApproving, setIsApproving] = useState(false)
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState<string>("ALL")
  const [stageFilter, setStageFilter] = useState<string>("ALL")

  type SortCol = "title" | "user" | "location" | "createdAt" | "status" | "stage"
  const [sortCol, setSortCol] = useState<SortCol>("createdAt")
  const [sortAsc, setSortAsc] = useState<boolean>(false)

  const filteredEntries = entries.filter((entry) => {
    // 1. Status Filter
    if (statusFilter !== "ALL" && entry.status !== statusFilter) {
      return false
    }

    // 2. Stage Filter
    if (stageFilter !== "ALL" && entry.stage !== Number(stageFilter)) {
      return false
    }

    // 3. Search Filter (free text)
    if (searchTerm) {
      const term = searchTerm.toLowerCase()
      const matchTitle = (entry.title || "").toLowerCase().includes(term)
      const matchSubject = (entry.subjectName || "").toLowerCase().includes(term)
      const matchCity = (entry.city || "").toLowerCase().includes(term)
      const matchCounty = (entry.county || "").toLowerCase().includes(term)
      const matchUser = (entry.user.name || "").toLowerCase().includes(term) || (entry.user.email || "").toLowerCase().includes(term) || (entry.user.class || "").toLowerCase().includes(term)
      const matchStatus = (entry.status || "").toLowerCase().includes(term)
      const matchDate = new Date(entry.createdAt).toLocaleDateString("ro-RO").includes(term)
      const matchStage = `etapa ${entry.stage}`.includes(term)

      if (!matchTitle && !matchSubject && !matchCity && !matchCounty && !matchUser && !matchStatus && !matchDate && !matchStage) {
        return false
      }
    }

    return true
  })

  // Sorting
  const sortedEntries = [...filteredEntries].sort((a, b) => {
    let aVal: any
    let bVal: any
    
    if (sortCol === "createdAt") {
      aVal = new Date(a.createdAt).getTime()
      bVal = new Date(b.createdAt).getTime()
    } else if (sortCol === "title") {
      aVal = a.title
      bVal = b.title
    } else if (sortCol === "user") {
      aVal = a.user.name || a.user.email
      bVal = b.user.name || b.user.email
    } else if (sortCol === "location") {
      aVal = a.city || a.county
      bVal = b.city || b.county
    } else if (sortCol === "status") {
      aVal = a.status
      bVal = b.status
    } else if (sortCol === "stage") {
      aVal = a.stage
      bVal = b.stage
    }

    if (aVal === bVal) return 0
    if (aVal === null || aVal === undefined) return 1
    if (bVal === null || bVal === undefined) return -1
    
    if (typeof aVal === "string" && typeof bVal === "string") {
      return sortAsc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal)
    }

    if (aVal < bVal) return sortAsc ? -1 : 1
    if (aVal > bVal) return sortAsc ? 1 : -1
    return 0
  })

  const handleSort = (col: SortCol) => {
    if (sortCol === col) setSortAsc(!sortAsc)
    else {
      setSortCol(col)
      setSortAsc(col === "createdAt" ? false : true)
    }
  }

  const SortIndicator = ({ col }: { col: SortCol }) => {
    if (sortCol !== col) return <span style={{ marginLeft: "0.25rem", opacity: 0.3 }}>⇅</span>
    return <span style={{ marginLeft: "0.25rem", color: "var(--primary)" }}>{sortAsc ? "↑" : "↓"}</span>
  }

  const handleSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.checked) {
      const newSet = new Set(selectedIds)
      filteredEntries.forEach(s => newSet.add(s.id))
      setSelectedIds(newSet)
    } else {
      const newSet = new Set(selectedIds)
      filteredEntries.forEach(s => newSet.delete(s.id))
      setSelectedIds(newSet)
    }
  }

  const handleSelectOne = (id: string) => {
    const newSet = new Set(selectedIds)
    if (newSet.has(id)) {
      newSet.delete(id)
    } else {
      newSet.add(id)
    }
    setSelectedIds(newSet)
  }

  const handleDeleteSelected = async () => {
    if (selectedIds.size === 0) return
    if (!window.confirm(`Sunteți sigur că doriți să ascundeți '${selectedIds.size}' intrări selectate?\nEle vor fi mutate în Coșul de Reciclare (Setări), de unde pot fi recuperate sau șterse definitiv.`)) {
      return
    }

    setIsDeleting(true)
    try {
      await bulkDeleteEntriesAction(Array.from(selectedIds))
      setSelectedIds(new Set())
      router.refresh()
    } catch (err) {
      alert("A apărut o eroare la stergere.")
    } finally {
      setIsDeleting(false)
    }
  }

  const handleApproveSelected = async () => {
    if (selectedIds.size === 0) return
    if (!window.confirm(`Sunteți sigur că doriți să aprobați și să publicați '${selectedIds.size}' intrări selectate?`)) {
      return
    }

    setIsApproving(true)
    try {
      await bulkApproveEntriesAction(Array.from(selectedIds))
      setSelectedIds(new Set())
      router.refresh()
    } catch (err) {
      alert("A apărut o eroare la aprobare.")
    } finally {
      setIsApproving(false)
    }
  }

  const isAllSelected = filteredEntries.length > 0 && selectedIds.size === filteredEntries.length
  const isIndeterminate = selectedIds.size > 0 && selectedIds.size < filteredEntries.length

  return (
    <>
      <style>{`
        .sortable-header {
          transition: background-color 0.2s ease, color 0.2s ease;
        }
        .sortable-header:hover {
          background-color: var(--primary-light);
          color: var(--primary) !important;
        }
      `}</style>
      {/* Pills filter by Status + Stage */}
      <div style={{ display: "flex", gap: "0.5rem", marginBottom: "1rem", flexWrap: "wrap", alignItems: "center" }}>
        <span style={{ fontSize: "0.9rem", color: "var(--text-muted)", fontWeight: 500, marginRight: "0.5rem" }}>Status:</span>
        {["ALL", "SUBMITTED", "APPROVED", "REJECTED"].map((status) => (
          <button
            key={status}
            onClick={() => setStatusFilter(status)}
            style={{
              padding: "0.4rem 0.8rem",
              borderRadius: "999px",
              border: "1px solid",
              background: statusFilter === status ? "var(--primary)" : "var(--surface-color)",
              color: statusFilter === status ? "white" : "var(--text-main)",
              borderColor: statusFilter === status ? "var(--primary)" : "var(--border-color)",
              fontSize: "0.85rem",
              fontWeight: statusFilter === status ? 600 : 400,
              cursor: "pointer",
            }}
          >
            {status === "ALL" ? "Toate" : status}
          </button>
        ))}

        <span style={{ width: "1px", height: "1.5rem", background: "var(--border-color)", margin: "0 0.5rem" }} />

        <span style={{ fontSize: "0.9rem", color: "var(--text-muted)", fontWeight: 500, marginRight: "0.5rem" }}>Etapă:</span>
        {[{ key: "ALL", label: "Toate" }, { key: "1", label: "Etapa 1" }, { key: "2", label: "Etapa 2" }].map((sf) => (
          <button
            key={sf.key}
            onClick={() => setStageFilter(sf.key)}
            style={{
              padding: "0.4rem 0.8rem",
              borderRadius: "999px",
              border: "1px solid",
              background: stageFilter === sf.key ? "#8b5cf6" : "var(--surface-color)",
              color: stageFilter === sf.key ? "white" : "var(--text-main)",
              borderColor: stageFilter === sf.key ? "#8b5cf6" : "var(--border-color)",
              fontSize: "0.85rem",
              fontWeight: stageFilter === sf.key ? 600 : 400,
              cursor: "pointer",
            }}
          >
            {sf.label}
          </button>
        ))}
      </div>

      <div style={{ background: "var(--surface-color)", borderRadius: "var(--radius-lg)", border: "1px solid var(--border-color)", overflow: "hidden" }}>
        {/* Header & Bulk Actions */}
        <div style={{ padding: "1.25rem 1.5rem", borderBottom: "1px solid var(--border-color)", display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", gap: "1rem" }}>
          <div style={{ display: "flex", alignItems: "center", gap: "1rem", flexWrap: "wrap" }}>
            <h2 style={{ fontSize: "1.15rem", fontWeight: 600, display: "flex", alignItems: "center", gap: "0.5rem", margin: 0 }}>
              Tabel Intrări Elevi ({filteredEntries.length})
              {selectedIds.size > 0 && (
                <span style={{ fontSize: "0.85rem", background: "var(--primary-light)", color: "var(--primary)", padding: "0.2rem 0.6rem", borderRadius: "999px" }}>
                  {selectedIds.size} selectate
                </span>
              )}
            </h2>

            <input 
              type="search" 
              placeholder="Caută obiectiv, elev, locație, dată, status..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              style={{
                padding: "0.4rem 0.8rem",
                borderRadius: "var(--radius-sm)",
                border: "1px solid var(--border-color)",
                background: "var(--surface-hover)",
                color: "var(--text-main)",
                fontSize: "0.85rem",
                minWidth: "300px"
              }}
            />
          </div>

          {selectedIds.size > 0 && (
            <div style={{ display: "flex", gap: "0.75rem", alignItems: "center" }}>
              <button 
                onClick={() => setSelectedIds(new Set())}
                style={{ padding: "0.4rem 0.75rem", fontSize: "0.85rem", background: "none", border: "1px solid var(--border-color)", borderRadius: "var(--radius-sm)", cursor: "pointer", color: "var(--text-main)" }}
              >
                Deselectează tot
              </button>

              <button 
                onClick={handleApproveSelected}
                disabled={isApproving || isDeleting}
                style={{ padding: "0.4rem 0.75rem", fontSize: "0.85rem", background: "var(--success)", color: "white", border: "none", borderRadius: "var(--radius-sm)", cursor: isApproving || isDeleting ? "wait" : "pointer", fontWeight: 500, display: "flex", alignItems: "center", gap: "0.3rem", opacity: isApproving || isDeleting ? 0.6 : 1 }}
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
                {isApproving ? "Se aprobă..." : "Aprobă"}
              </button>

              <button 
                onClick={handleDeleteSelected}
                disabled={isDeleting || isApproving}
                style={{ padding: "0.4rem 0.75rem", fontSize: "0.85rem", background: "var(--danger)", color: "white", border: "none", borderRadius: "var(--radius-sm)", cursor: isDeleting || isApproving ? "wait" : "pointer", fontWeight: 500, display: "flex", alignItems: "center", gap: "0.3rem", opacity: isDeleting || isApproving ? 0.6 : 1 }}
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
                {isDeleting ? "Se șterg..." : "Șterge"}
              </button>
            </div>
          )}
        </div>

        {/* Table layout */}
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", textAlign: "left" }}>
            <thead>
              <tr style={{ background: "var(--surface-hover)" }}>
                <th style={{ padding: "1rem 1.5rem", width: "40px" }}>
                  <input 
                    type="checkbox" 
                    checked={isAllSelected}
                    ref={(input) => { if (input) input.indeterminate = isIndeterminate }}
                    onChange={handleSelectAll}
                    style={{ cursor: "pointer", width: "16px", height: "16px", accentColor: "var(--primary)" }}
                  />
                </th>
                {[
                  { key: "title", label: "Obiectiv" },
                  { key: "user", label: "Elev" },
                  { key: "location", label: "Locație" },
                  { key: "stage", label: "Etapă" },
                  { key: "createdAt", label: "Data" },
                  { key: "status", label: "Status" }
                ].map((h) => (
                  <th 
                    key={h.key} 
                    className="sortable-header"
                    onClick={() => handleSort(h.key as SortCol)}
                    style={{ padding: "1rem 1.5rem", fontSize: "0.85rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase", cursor: "pointer", userSelect: "none", borderBottom: "1px solid transparent" }}
                  >
                    {h.label} <SortIndicator col={h.key as SortCol} />
                  </th>
                ))}
                <th style={{ padding: "1rem 1.5rem", fontSize: "0.85rem", color: "var(--text-muted)", fontWeight: 600, textTransform: "uppercase", textAlign: "right" }}>Acțiuni</th>
              </tr>
            </thead>
            <tbody>
              {sortedEntries.map((entry) => (
                <tr 
                  key={entry.id} 
                  style={{ 
                    borderBottom: "1px solid var(--border-color)",
                    background: selectedIds.has(entry.id) ? "var(--surface-hover)" : "transparent"
                  }}
                >
                  <td style={{ padding: "1rem 1.5rem" }}>
                    <input 
                      type="checkbox"
                      checked={selectedIds.has(entry.id)}
                      onChange={() => handleSelectOne(entry.id)}
                      style={{ cursor: "pointer", width: "16px", height: "16px", accentColor: "var(--primary)" }}
                    />
                  </td>
                  <td style={{ padding: "1rem 1.5rem" }} onClick={() => handleSelectOne(entry.id)}>
                    <div style={{ fontWeight: 500, color: "var(--text-main)", marginBottom: "0.25rem" }}>{entry.title}</div>
                    <div style={{ fontSize: "0.85rem", color: "var(--text-muted)" }}>{entry.subjectName}</div>
                  </td>
                  <td style={{ padding: "1rem 1.5rem" }} onClick={() => handleSelectOne(entry.id)}>
                    <div style={{ fontWeight: 500, color: "var(--text-main)", marginBottom: "0.25rem" }}>{entry.user.name}</div>
                    <div style={{ fontSize: "0.85rem", color: "var(--text-muted)" }}>Cls a {entry.user.class}-a</div>
                  </td>
                  <td style={{ padding: "1rem 1.5rem", fontSize: "0.9rem", color: "var(--text-muted)" }} onClick={() => handleSelectOne(entry.id)}>
                    {entry.city}, {entry.county}
                  </td>
                  <td style={{ padding: "1rem 1.5rem" }} onClick={() => handleSelectOne(entry.id)}>
                    <span style={{
                      fontSize: "0.75rem",
                      padding: "0.2rem 0.55rem",
                      borderRadius: "999px",
                      background: entry.stage === 1 ? "rgba(139, 92, 246, 0.1)" : "rgba(59, 130, 246, 0.1)",
                      color: entry.stage === 1 ? "#8b5cf6" : "#3b82f6",
                      fontWeight: 600,
                    }}>
                      {entry.stage}
                    </span>
                  </td>
                  <td style={{ padding: "1rem 1.5rem", fontSize: "0.9rem", color: "var(--text-muted)" }} onClick={() => handleSelectOne(entry.id)}>
                    {new Date(entry.createdAt).toLocaleDateString("ro-RO")}
                  </td>
                  <td style={{ padding: "1rem 1.5rem" }} onClick={() => handleSelectOne(entry.id)}>
                    <span style={{ 
                      fontSize: "0.75rem", 
                      padding: "0.25rem 0.6rem", 
                      borderRadius: "999px",
                      background: entry.status === "APPROVED" ? "rgba(16, 185, 129, 0.1)" : 
                                  entry.status === "REJECTED" ? "rgba(239, 68, 68, 0.1)" : 
                                  entry.status === "SUBMITTED" ? "rgba(245, 158, 11, 0.1)" : "rgba(100, 116, 139, 0.1)",
                      color: entry.status === "APPROVED" ? "var(--success)" : 
                             entry.status === "REJECTED" ? "var(--danger)" : 
                             entry.status === "SUBMITTED" ? "var(--warning)" : "var(--text-muted)",
                      fontWeight: 600
                    }}>
                      {entry.status}
                    </span>
                  </td>
                  <td style={{ padding: "1rem 1.5rem", textAlign: "right" }}>
                    <Link 
                      href={`/admin/entry/${entry.id}`}
                      style={{ 
                        color: "var(--primary)", 
                        fontSize: "0.9rem", 
                        fontWeight: 500,
                        padding: "0.4rem 0.8rem",
                        borderRadius: "var(--radius-sm)",
                        background: "var(--primary-light)",
                        display: "inline-block",
                        textDecoration: "none"
                      }}
                      onClick={e => e.stopPropagation()}
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ display: "block", margin: "0 auto" }}>
                        <path d="m15 5 4 4"/>
                        <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z"/>
                      </svg>
                    </Link>
                  </td>
                </tr>
              ))}
              {filteredEntries.length === 0 && (
                <tr>
                  <td colSpan={8} style={{ padding: "3rem", textAlign: "center", color: "var(--text-muted)" }}>
                    {entries.length === 0 ? "Nicio intrare găsită în baza de date." : "Filtrarea nu returnează rezultate."}
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </>
  )
}
