import type { Meta, StoryObj } from '@storybook/react'
import React, { useState } from 'react'
import { BadgeStatus } from './Badge'
import { Pagination, Table } from './Table'

const meta: Meta = {
  title: 'Components/Table',
  parameters: { layout: 'centered' },
}
export default meta

type Row = { id: number; name: string; status: string; usage: string; updated: string }

const data: Row[] = Array.from({ length: 20 }, (_, i) => ({
  id: i + 1,
  name: ['회의록 요약', '이미지 분석', '코드 리뷰', '번역 도구', '데이터 정제'][i % 5] + ` v${i + 1}`,
  status: ['active', 'in-progress', 'pending', 'error', 'inactive'][i % 5],
  usage: `${(i + 1) * 37}건`,
  updated: `2026.03.${String(i + 1).padStart(2, '0')}`,
}))

const statusMap: Record<string, React.ReactNode> = {
  active: <BadgeStatus status="active">활성</BadgeStatus>,
  'in-progress': <BadgeStatus status="in-progress">처리중</BadgeStatus>,
  pending: <BadgeStatus status="pending">대기</BadgeStatus>,
  error: <BadgeStatus status="error">오류</BadgeStatus>,
  inactive: <BadgeStatus status="inactive">비활성</BadgeStatus>,
}

export const BasicTable: StoryObj = {
  name: 'Table',
  render: () => {
    const [page, setPage] = useState(1)
    const [query, setQuery] = useState('')
    const pageSize = 5
    const filtered = data.filter((r) => r.name.includes(query))
    const pageData = filtered.slice((page - 1) * pageSize, page * pageSize)

    return (
      <div className="w-[700px]">
        <Table<Row>
          title="도구 목록"
          totalCount={filtered.length}
          columns={[
            { key: 'name', label: '도구명', width: '2fr' },
            { key: 'status', label: '상태', width: '100px', render: (_, row) => statusMap[row.status] },
            { key: 'usage', label: '사용량', width: '80px' },
            { key: 'updated', label: '수정일', width: '100px' },
          ]}
          data={pageData}
          onSearch={(q) => { setQuery(q); setPage(1) }}
          onFilter={() => {}}
          currentPage={page}
          totalPages={Math.ceil(filtered.length / pageSize)}
          totalCount={filtered.length}
          pageSize={pageSize}
          onPageChange={setPage}
        />
      </div>
    )
  },
}

export const PaginationStory: StoryObj = {
  name: 'Pagination',
  render: () => {
    const [page, setPage] = useState(1)
    return (
      <div className="w-[480px] space-y-4">
        <Pagination currentPage={page} totalPages={15} totalCount={147} pageSize={10} onPageChange={setPage} />
      </div>
    )
  },
}
