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

const fetchMitras = async () => {
  const res = await apiClient.get('/internal/mitras')
  return res.data.data
}

const fetchOnlineMitras = async () => {
  const res = await apiClient.get('/internal/mitras/online')
  return res.data.data
}

const createMitra = async (data) => {
  const res = await apiClient.post('/internal/mitras', data)
  return res.data.data
}

const updateMitraStatus = async ({ id, is_active }) => {
  const res = await apiClient.patch(`/internal/mitras/${id}/status`, { is_active })
  return res.data.data
}

const fetchOnlineLogs = async (mitraId) => {
  const res = await apiClient.get(`/internal/mitras/${mitraId}/online-logs`)
  return res.data.data
}

export default function MitrasPage() {
  const queryClient = useQueryClient()
  const { data, isLoading } = useQuery({ queryKey: ['mitras'], queryFn: fetchMitras })
  const { data: onlineData } = useQuery({
    queryKey: ['mitras-online'],
    queryFn: fetchOnlineMitras,
    refetchInterval: 10000,
  })

  const [form, setForm] = useState({ phone: '', display_name: '' })
  const [showForm, setShowForm] = useState(false)
  const [logsForMitra, setLogsForMitra] = useState(null)

  const { data: logsData, isLoading: logsLoading } = useQuery({
    queryKey: ['mitra-online-logs', logsForMitra],
    queryFn: () => fetchOnlineLogs(logsForMitra),
    enabled: !!logsForMitra,
  })

  const createMutation = useMutation({
    mutationFn: createMitra,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mitras'] })
      setForm({ phone: '', display_name: '' })
      setShowForm(false)
    },
  })

  const statusMutation = useMutation({
    mutationFn: updateMitraStatus,
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['mitras'] }),
  })

  if (isLoading) return <div>Loading...</div>

  // Build a set of online mitra IDs for quick lookup
  const onlineMitraMap = new Map()
  for (const m of onlineData ?? []) {
    onlineMitraMap.set(m.id, m)
  }

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>Mitra</h1>
        <button onClick={() => setShowForm(!showForm)}>+ Tambah Mitra</button>
      </div>

      {showForm && (
        <form onSubmit={(e) => { e.preventDefault(); createMutation.mutate(form) }}
          style={{ marginBottom: 24, padding: 16, border: '1px solid #eee' }}>
          <h3>Tambah Mitra Baru</h3>
          <input placeholder="Nomor HP (+628...)" value={form.phone}
            onChange={e => setForm(f => ({ ...f, phone: e.target.value }))} required
            style={{ display: 'block', marginBottom: 8, width: '100%' }} />
          <input placeholder="Nama" value={form.display_name}
            onChange={e => setForm(f => ({ ...f, display_name: e.target.value }))} required
            style={{ display: 'block', marginBottom: 8, width: '100%' }} />
          <button type="submit" disabled={createMutation.isPending}>
            {createMutation.isPending ? 'Menyimpan...' : 'Simpan'}
          </button>
          {createMutation.isError && <p style={{ color: 'red' }}>Gagal menyimpan.</p>}
        </form>
      )}

      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Nama</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Nomor HP</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Status Akun</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Online</th>
            <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Sesi Aktif</th>
            <th style={{ padding: 8, borderBottom: '1px solid #eee' }}>Aksi</th>
          </tr>
        </thead>
        <tbody>
          {data?.items?.map((mitra) => {
            const onlineInfo = onlineMitraMap.get(mitra.id)
            return (
              <tr key={mitra.id}>
                <td style={{ padding: 8 }}>{mitra.display_name}</td>
                <td style={{ padding: 8 }}>{mitra.phone}</td>
                <td style={{ padding: 8 }}>{mitra.is_active ? 'Aktif' : 'Nonaktif'}</td>
                <td style={{ padding: 8 }}>
                  <span style={{ color: onlineInfo ? 'green' : 'grey' }}>
                    {onlineInfo ? '● Online' : '○ Offline'}
                  </span>
                </td>
                <td style={{ padding: 8 }}>{onlineInfo ? onlineInfo.active_session_count : '-'}</td>
                <td style={{ padding: 8, display: 'flex', gap: 8 }}>
                  <button onClick={() => statusMutation.mutate({ id: mitra.id, is_active: !mitra.is_active })}>
                    {mitra.is_active ? 'Nonaktifkan' : 'Aktifkan'}
                  </button>
                  <button onClick={() => setLogsForMitra(logsForMitra === mitra.id ? null : mitra.id)}>
                    {logsForMitra === mitra.id ? 'Tutup Log' : 'Log Online'}
                  </button>
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>

      {logsForMitra && (
        <div style={{ marginTop: 16, padding: 16, border: '1px solid #eee' }}>
          <h3>Log Online/Offline</h3>
          {logsLoading ? (
            <p>Loading...</p>
          ) : (
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Status</th>
                  <th style={{ textAlign: 'left', padding: 8, borderBottom: '1px solid #eee' }}>Waktu</th>
                </tr>
              </thead>
              <tbody>
                {logsData?.items?.map((log) => (
                  <tr key={log.id}>
                    <td style={{ padding: 8 }}>
                      <span style={{ color: log.status === 'online' ? 'green' : 'grey' }}>
                        {log.status === 'online' ? '● Online' : '○ Offline'}
                      </span>
                    </td>
                    <td style={{ padding: 8 }}>{new Date(log.timestamp).toLocaleString('id-ID')}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}
    </div>
  )
}
