import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '../../core/api/api-client'
import {
  PairingFailureCause,
  PairingFailureCauseLabel,
  PairingFailureOperatorAction,
  PairingFailureOperatorActionLabel,
} from '../../core/constants'

const PAGE_SIZE = 50

const CAUSE_OPTIONS = Object.values(PairingFailureCause).map((value) => ({
  value,
  label: PairingFailureCauseLabel[value],
}))

const fetchFailedPairings = async ({ causeTags, dateFrom, dateTo, limit, offset }) => {
  const params = new URLSearchParams()
  for (const tag of causeTags) params.append('cause_tags', tag)
  if (dateFrom) params.set('date_from', dateFrom)
  if (dateTo) params.set('date_to', dateTo)
  params.set('limit', String(limit))
  params.set('offset', String(offset))
  const res = await apiClient.get(`/internal/failed-pairings?${params}`)
  return res.data.data
}

const submitOperatorAction = async ({ id, action }) => {
  const res = await apiClient.post(`/internal/failed-pairings/${id}/action`, { action })
  return res.data.data
}

const formatRupiah = (amount) => {
  if (amount === null || amount === undefined) return '-'
  return `Rp ${Number(amount).toLocaleString('id-ID')}`
}

const formatDateTime = (iso) => {
  if (!iso) return '-'
  return new Date(iso).toLocaleString('id-ID')
}

const operatorActionLabel = (row) => {
  if (!row.operator_action) return '-'
  return PairingFailureOperatorActionLabel[row.operator_action] ?? row.operator_action
}

export default function FailedPairingsPage() {
  const queryClient = useQueryClient()
  const [selectedCauses, setSelectedCauses] = useState([])
  const [dateFrom, setDateFrom] = useState('')
  const [dateTo, setDateTo] = useState('')
  const [page, setPage] = useState(1)
  const [openMenuId, setOpenMenuId] = useState(null)

  const offset = (page - 1) * PAGE_SIZE

  const { data, isLoading, isError } = useQuery({
    queryKey: ['failed-pairings', selectedCauses, dateFrom, dateTo, page],
    queryFn: () => fetchFailedPairings({
      causeTags: selectedCauses,
      dateFrom: dateFrom || null,
      dateTo: dateTo || null,
      limit: PAGE_SIZE,
      offset,
    }),
    keepPreviousData: true,
  })

  const actionMutation = useMutation({
    mutationFn: submitOperatorAction,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['failed-pairings'] })
      setOpenMenuId(null)
    },
  })

  const toggleCause = (value) => {
    setPage(1)
    setSelectedCauses((prev) =>
      prev.includes(value) ? prev.filter((v) => v !== value) : [...prev, value],
    )
  }

  const clearFilters = () => {
    setSelectedCauses([])
    setDateFrom('')
    setDateTo('')
    setPage(1)
  }

  const total = data?.total ?? 0
  const rows = data?.rows ?? []
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE))

  return (
    <div>
      <h1>Failed Pairings</h1>

      <div style={{ marginBottom: 16, padding: 12, border: '1px solid #eee', display: 'flex', flexDirection: 'column', gap: 12 }}>
        <div>
          <strong style={{ marginRight: 8 }}>Cause:</strong>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 4 }}>
            {CAUSE_OPTIONS.map((opt) => (
              <label key={opt.value} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 13 }}>
                <input
                  type="checkbox"
                  checked={selectedCauses.includes(opt.value)}
                  onChange={() => toggleCause(opt.value)}
                />
                {opt.label}
              </label>
            ))}
          </div>
        </div>

        <div style={{ display: 'flex', gap: 16, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <label style={{ fontSize: 13 }}>From:</label>
            <input
              type="date"
              value={dateFrom}
              onChange={(e) => { setDateFrom(e.target.value); setPage(1) }}
            />
          </div>
          <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <label style={{ fontSize: 13 }}>To:</label>
            <input
              type="date"
              value={dateTo}
              onChange={(e) => { setDateTo(e.target.value); setPage(1) }}
            />
          </div>
          <button onClick={clearFilters} style={{ fontSize: 12 }}>Clear filters</button>
        </div>
      </div>

      {isLoading && <div>Loading...</div>}
      {isError && <p style={{ color: 'red' }}>Gagal memuat data failed pairings.</p>}

      {!isLoading && !isError && (
        <>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Created</th>
                <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Customer</th>
                <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Targeted Mitra</th>
                <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Cause</th>
                <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Amount</th>
                <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Operator Action</th>
                <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Actioned By</th>
                <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Actioned At</th>
                <th style={{ padding: 8, borderBottom: '1px solid #eee' }}>Aksi</th>
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 && (
                <tr>
                  <td colSpan={9} style={{ padding: 24, textAlign: 'center', color: '#666' }}>
                    Belum ada data failed pairings.
                  </td>
                </tr>
              )}
              {rows.map((row) => {
                const canAction = !row.operator_action
                return (
                  <tr key={row.id}>
                    <td style={{ padding: 8 }}>{formatDateTime(row.created_at)}</td>
                    <td style={{ padding: 8 }}>{row.customer_call_name ?? '-'}</td>
                    <td style={{ padding: 8 }}>{row.targeted_mitra_call_name ?? '-'}</td>
                    <td style={{ padding: 8 }}>
                      {PairingFailureCauseLabel[row.cause_tag] ?? row.cause_tag}
                    </td>
                    <td style={{ padding: 8 }}>{formatRupiah(row.amount)}</td>
                    <td style={{ padding: 8 }}>{operatorActionLabel(row)}</td>
                    <td style={{ padding: 8 }}>{row.actioned_by_name ?? '-'}</td>
                    <td style={{ padding: 8 }}>{formatDateTime(row.actioned_at)}</td>
                    <td style={{ padding: 8, position: 'relative' }}>
                      {canAction ? (
                        <>
                          <button
                            onClick={() => setOpenMenuId(openMenuId === row.id ? null : row.id)}
                            disabled={actionMutation.isPending}
                            style={{ fontSize: 12 }}
                          >
                            Action
                          </button>
                          {openMenuId === row.id && (
                            <div style={{
                              position: 'absolute',
                              right: 8,
                              top: '100%',
                              background: 'white',
                              border: '1px solid #ddd',
                              boxShadow: '0 2px 6px rgba(0,0,0,0.08)',
                              zIndex: 10,
                              minWidth: 180,
                            }}>
                              <button
                                style={menuItemStyle}
                                onClick={() => actionMutation.mutate({ id: row.id, action: PairingFailureOperatorAction.REFUNDED })}
                              >
                                Mark as refunded
                              </button>
                              <button
                                style={menuItemStyle}
                                onClick={() => actionMutation.mutate({ id: row.id, action: PairingFailureOperatorAction.CREDITED })}
                              >
                                Mark as credited
                              </button>
                              <button
                                style={menuItemStyle}
                                onClick={() => actionMutation.mutate({ id: row.id, action: PairingFailureOperatorAction.NO_ACTION })}
                              >
                                Mark as no-action
                              </button>
                            </div>
                          )}
                        </>
                      ) : (
                        <span style={{ color: '#999', fontSize: 12 }}>—</span>
                      )}
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>

          <div style={{ marginTop: 16, display: 'flex', gap: 8, justifyContent: 'center', alignItems: 'center' }}>
            <button disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>Prev</button>
            <span>Page {page} of {totalPages} ({total} total)</span>
            <button disabled={page >= totalPages} onClick={() => setPage((p) => p + 1)}>Next</button>
          </div>
        </>
      )}

      {actionMutation.isError && (
        <p style={{ color: 'red', marginTop: 8 }}>Gagal menyimpan operator action.</p>
      )}
    </div>
  )
}

const menuItemStyle = {
  display: 'block',
  width: '100%',
  padding: '8px 12px',
  background: 'white',
  border: 'none',
  borderBottom: '1px solid #f0f0f0',
  textAlign: 'left',
  cursor: 'pointer',
  fontSize: 13,
}
