'use client'

import Link from 'next/link'
import {
  Badge,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeadCell,
  TableRow,
} from 'flowbite-react'
import { FiExternalLink, FiEye } from 'react-icons/fi'

import { FollowUpRating } from '@/app/(dashboard)/follow-up-ratings/types'
import badgeTheme from '@/lib/themes/badge'
import tableTheme from '@/lib/themes/table'
import { formatDuration, formatToMYT } from '@/lib/utils/date'
import {
  formatTransactionTypeLabel,
  getResourceDetailUrl,
} from '@/lib/utils/user-performance'
import { FollowUpHistoryRow } from '../types'

interface FollowUpHistoryTableProps {
  rows: FollowUpHistoryRow[]
  isLoading: boolean
  ratings: FollowUpRating[]
}

export default function FollowUpHistoryTable({
  rows,
  isLoading,
  ratings,
}: FollowUpHistoryTableProps) {
  return (
    <div className="min-h-48 overflow-x-auto rounded-lg border border-slate-200">
      <Table theme={tableTheme.table} hoverable>
        <TableHead>
          <TableRow>
            <TableHeadCell className="text-nowrap p-4">Merchant</TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Transaction Type
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Invoice Number
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Transaction/Request Date
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Follow Up Time
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Response Time
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">Rating</TableHeadCell>
            <TableHeadCell className="text-nowrap p-4">
              Follow Up Link
            </TableHeadCell>
            <TableHeadCell className="text-nowrap p-4 text-center">
              Action
            </TableHeadCell>
          </TableRow>
        </TableHead>

        <TableBody className="divide-y divide-gray-200">
          {isLoading ? (
            Array.from({ length: 5 }).map((_, index) => (
              <TableRow key={`skeleton-${index}`} className="bg-white">
                {Array.from({ length: 9 }).map((__, cellIndex) => (
                  <TableCell key={`skeleton-cell-${cellIndex}`} className="p-4">
                    <div className="h-4 w-24 animate-pulse rounded bg-slate-200" />
                  </TableCell>
                ))}
              </TableRow>
            ))
          ) : rows.length === 0 ? (
            <TableRow className="bg-white">
              <TableCell
                colSpan={10}
                className="p-8 text-center text-slate-400"
              >
                No follow-up history matches the selected filters.
              </TableCell>
            </TableRow>
          ) : (
            rows.map((row) => {
              const rating = ratings.find((item) => item.id === row.rating_id)

              return (
                <TableRow key={row.follow_up_id} className="bg-white">
                  <TableCell className="p-4 text-nowrap font-medium text-slate-900">
                    {row.merchant_name}
                  </TableCell>
                  <TableCell className="p-4 text-nowrap">
                    {formatTransactionTypeLabel(row.transaction_type)}
                  </TableCell>
                  <TableCell className="p-4 text-nowrap">
                    {row.invoice_number || '-'}
                  </TableCell>
                  <TableCell className="p-4 text-nowrap">
                    {formatToMYT(
                      row.transaction_date,
                      "MMMM dd, yyyy 'at' HH:mm",
                    )}
                  </TableCell>
                  <TableCell className="p-4 text-nowrap">
                    {formatToMYT(
                      row.followed_up_at,
                      "MMMM dd, yyyy 'at' HH:mm",
                    )}
                  </TableCell>
                  <TableCell className="p-4 font-mono text-sm tabular-nums text-nowrap">
                    {formatDuration(row.response_seconds)}
                  </TableCell>
                  <TableCell className="p-4">
                    <Badge
                      theme={badgeTheme.badge}
                      color="none"
                      className="max-w-full whitespace-nowrap"
                      style={{
                        backgroundColor: rating?.background_color ?? '#e2e8f0',
                        color: rating?.text_color ?? '#475569',
                      }}
                    >
                      {rating?.label ?? row.rating_label ?? '-'}
                    </Badge>
                  </TableCell>
                  <TableCell className="p-4">
                    {row.evidence_url ? (
                      <a
                        href={row.evidence_url}
                        target="_blank"
                        rel="noreferrer noopener"
                        className="inline-flex items-center gap-1 text-nowrap text-blue-600 hover:underline"
                      >
                        Open Evidence
                        <FiExternalLink className="h-4 w-4" />
                      </a>
                    ) : (
                      <span className="text-slate-400">-</span>
                    )}
                  </TableCell>
                  <TableCell className="p-4 text-center">
                    <Link
                      href={getResourceDetailUrl(
                        row.merchant_id,
                        row.transaction_type,
                        row.resource_id,
                      )}
                      className="inline-flex items-center gap-1 rounded-md p-2 text-primary hover:bg-slate-100"
                      aria-label="View resource detail"
                      title="View Resource Detail"
                    >
                      <FiEye className="h-4 w-4" />
                    </Link>
                  </TableCell>
                </TableRow>
              )
            })
          )}
        </TableBody>
      </Table>
    </div>
  )
}
