import { useEffect, useState } from 'react'
import { worklogList, worklogProgress, createWorklog, worklogDetail, deleteWorklog, addWorklogComment } from '../../api/uiws'
import { PageHeader, SearchBar, Input, Button, DataGrid, Pagination, Modal, FormField, Spinner, type Column } from '../../components/uiws/ui'

interface WorklogRow extends Record<string, unknown> {
  worklogId: number; title: string; writerNm: string; workDate: string; progressCd: string; commentCount: number
}

const PROGRESS_LABEL: Record<string, string> = { ONGOING: '진행중', DONE: '종료' }

export default function WorklogList() {
  const [rows, setRows] = useState<WorklogRow[]>([])
  const [page, setPage] = useState(0)
  const [totalPages, setTotalPages] = useState(0)
  const [progress, setProgress] = useState<{ progressCd: string; progressNm: string; count: number }[]>([])
  const [filterProgress, setFilterProgress] = useState('')
  const [keyword, setKeyword] = useState('')
  const [loading, setLoading] = useState(false)
  const [showForm, setShowForm] = useState(false)
  const [detail, setDetail] = useState<any>(null)

  const load = async () => {
    setLoading(true)
    try {
      const res = await worklogList({ page, size: 20, progressCd: filterProgress || undefined })
      const data = res.data.data
      setRows(data.content ?? [])
      setTotalPages(data.totalPages ?? 0)
      const pr = await worklogProgress({})
      setProgress(pr.data.data ?? [])
    } finally {
      setLoading(false)
    }
  }
  useEffect(() => { load() }, [page, filterProgress])

  const columns: Column<WorklogRow>[] = [
    { key: 'workDate', header: '근무일자', width: 120 },
    { key: 'title', header: '제목' },
    { key: 'writerNm', header: '작성자', width: 120 },
    { key: 'progressCd', header: '진행', width: 90, render: r => PROGRESS_LABEL[r.progressCd] ?? r.progressCd },
    { key: 'commentCount', header: '댓글', width: 70, align: 'center' },
  ]

  const openDetail = async (r: WorklogRow) => {
    const res = await worklogDetail(r.worklogId)
    setDetail(res.data.data)
  }

  return (
    <div className="uiws-scope">
      <PageHeader title="업무일지" subtitle="UIWS 이식 · 업무일지 작성/조회/진행관리"
        actions={<Button onClick={() => setShowForm(true)}>+ 업무일지 작성</Button>} />

      <div style={{ display: 'flex', gap: 10, marginBottom: 16, flexWrap: 'wrap' }}>
        {progress.map(p => (
          <div key={p.progressCd} onClick={() => { setFilterProgress(filterProgress === p.progressCd ? '' : p.progressCd); setPage(0) }}
            style={{ cursor: 'pointer', padding: '12px 18px', borderRadius: 10, minWidth: 130,
              background: 'var(--uiws-surface)', border: `1px solid ${filterProgress === p.progressCd ? 'var(--uiws-primary)' : 'var(--uiws-border)'}` }}>
            <div style={{ fontSize: 12, color: 'var(--uiws-text-muted)' }}>{p.progressNm}</div>
            <div style={{ fontSize: 24, fontWeight: 700, color: 'var(--uiws-primary)' }}>{p.count}</div>
          </div>
        ))}
      </div>

      <SearchBar>
        <Input value={keyword} onChange={setKeyword} placeholder="제목 검색" style={{ minWidth: 220 }} />
        <Button variant="ghost" onClick={() => { setPage(0); load() }}>검색</Button>
        {filterProgress && <Button variant="ghost" onClick={() => setFilterProgress('')}>필터 해제: {PROGRESS_LABEL[filterProgress] ?? filterProgress}</Button>}
      </SearchBar>

      {loading ? <Spinner /> : (
        <>
          <DataGrid columns={columns} rows={rows} rowKey={r => r.worklogId} onRowClick={openDetail} empty="업무일지가 없습니다." />
          <Pagination page={page} totalPages={totalPages} onChange={setPage} />
        </>
      )}

      {showForm && <WorklogForm onClose={() => setShowForm(false)} onSaved={() => { setShowForm(false); load() }} />}
      {detail && <WorklogDetailModal detail={detail} onClose={() => setDetail(null)} onChanged={() => { setDetail(null); load() }} />}
    </div>
  )
}

function WorklogForm({ onClose, onSaved }: { onClose: () => void; onSaved: () => void }) {
  const [title, setTitle] = useState('')
  const [writerId, setWriterId] = useState(localStorage.getItem('mes_user') || 'admin')
  const [workDate, setWorkDate] = useState(new Date().toISOString().slice(0, 10))
  const [workStatusCd, setWorkStatusCd] = useState('NORMAL')
  const [err, setErr] = useState('')

  const save = async () => {
    setErr('')
    try {
      await createWorklog({ title, writerId, workDate, workStatusCd, progressCd: 'ONGOING', details: [] })
      onSaved()
    } catch (e: any) {
      setErr(e?.response?.data?.message || '저장 실패')
    }
  }
  return (
    <Modal title="업무일지 작성" onClose={onClose}
      footer={<><Button variant="ghost" onClick={onClose}>취소</Button><Button onClick={save}>저장</Button></>}>
      <FormField label="제목"><Input value={title} onChange={setTitle} style={{ width: '100%' }} /></FormField>
      <FormField label="작성자 ID"><Input value={writerId} onChange={setWriterId} style={{ width: '100%' }} /></FormField>
      <FormField label="근무일자"><Input type="date" value={workDate} onChange={setWorkDate} style={{ width: '100%' }} /></FormField>
      <FormField label="근무상태 코드"><Input value={workStatusCd} onChange={setWorkStatusCd} style={{ width: '100%' }} /></FormField>
      {err && <div style={{ color: 'var(--uiws-danger)', fontSize: 13 }}>{err}</div>}
    </Modal>
  )
}

function WorklogDetailModal({ detail, onClose, onChanged }: { detail: any; onClose: () => void; onChanged: () => void }) {
  const [comment, setComment] = useState('')
  const [err, setErr] = useState('')

  const remove = async () => {
    await deleteWorklog(detail.worklogId)
    onChanged()
  }
  const addCmt = async () => {
    setErr('')
    try {
      await addWorklogComment(detail.worklogId, comment)
      setComment('')
      onChanged()
    } catch (e: any) {
      setErr(e?.response?.data?.message || '댓글 등록 실패')
    }
  }
  return (
    <Modal title={detail.title} onClose={onClose}
      footer={<><Button variant="danger" onClick={remove}>삭제</Button><Button variant="ghost" onClick={onClose}>닫기</Button></>}>
      <div style={{ fontSize: 13, color: 'var(--uiws-text-muted)', marginBottom: 12 }}>
        {detail.writerNm} · {detail.workDate} · {detail.progressCd}
      </div>
      <div style={{ fontSize: 12, color: 'var(--uiws-text-muted)', marginBottom: 6 }}>시간대별 상세 {detail.details?.length ?? 0}건</div>
      <div style={{ marginTop: 14 }}>
        <div style={{ fontSize: 12, color: 'var(--uiws-text-muted)', marginBottom: 8 }}>댓글</div>
        {(detail.comments ?? []).map((c: any) => (
          <div key={c.cmtId} style={{ padding: '8px 10px', borderRadius: 8, background: 'var(--uiws-surface-2)', marginBottom: 6, fontSize: 13 }}>
            <b>{c.writerNm}</b> · <span style={{ color: 'var(--uiws-text-muted)' }}>{c.createdAt}</span><br />{c.cmtContent}
          </div>
        ))}
        <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
          <Input value={comment} onChange={setComment} placeholder="댓글 입력(관리자/매니저)" style={{ flex: 1 }} />
          <Button onClick={addCmt}>등록</Button>
        </div>
        {err && <div style={{ color: 'var(--uiws-danger)', fontSize: 12, marginTop: 6 }}>{err}</div>}
      </div>
    </Modal>
  )
}
