import { type FormEvent, useEffect, useState } from 'react'
import {
  deleteAttendanceCommentTemplate,
  fetchAttendanceCommentTemplates,
  saveAttendanceCommentTemplate,
} from '../../api/session'
import type { AttendanceCommentTemplate } from '../../api/types'

/** Port of `Views/attendance_templates/index.php` — comment templates CRUD. */
export function AttendanceTemplatesIndexPage() {
  const [templates, setTemplates] = useState<AttendanceCommentTemplate[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [modal, setModal] = useState<AttendanceCommentTemplate | null>(null)

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      setLoading(true)
      setError(null)
      try {
        const data = await fetchAttendanceCommentTemplates()
        if (!cancelled) setTemplates(data.templates ?? [])
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load templates.')
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  async function refreshTemplates() {
    try {
      const data = await fetchAttendanceCommentTemplates()
      setTemplates(data.templates ?? [])
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to load templates.')
    }
  }

  function openModal(t?: AttendanceCommentTemplate) {
    setModal(
      t ?? {
        id: undefined,
        min_score: undefined,
        max_score: undefined,
        template_text: '',
        is_active: true,
      },
    )
  }

  async function onSave(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!modal) return
    const fd = new FormData(e.currentTarget)
    const data: Record<string, string> = {}
    fd.forEach((v, k) => {
      data[k] = String(v)
    })
    if (modal.id != null) data.id = String(modal.id)
    data.is_active = fd.get('is_active') === 'on' ? 'on' : ''
    try {
      await saveAttendanceCommentTemplate(data)
      setModal(null)
      await refreshTemplates()
    } catch {
      setError('Save failed.')
    }
  }

  async function onDelete(id: number | undefined) {
    if (id == null) return
    if (!confirm('Delete this template?')) return
    try {
      await deleteAttendanceCommentTemplate(id)
      await refreshTemplates()
    } catch {
      setError('Delete failed.')
    }
  }

  return (
    <div className="container-fluid py-4">
      <div className="text-center mb-4">
        <h2 className="mt-2 mb-3">Attendance Comment Templates</h2>
      </div>

      <div className="mb-4">
        <button type="button" className="btn btn-success" onClick={() => openModal()}>
          Add New Template
        </button>
      </div>

      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="table-responsive">
        <table className="table table-striped align-middle">
          <thead>
            <tr>
              <th>ID</th>
              <th>Min Score</th>
              <th>Max Score</th>
              <th>Template Text</th>
              <th>Active</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={6} className="text-center text-muted">
                  Loading…
                </td>
              </tr>
            ) : templates.length === 0 ? (
              <tr>
                <td colSpan={6} className="text-center text-muted">
                  No templates.
                </td>
              </tr>
            ) : (
              templates.map((t, ti) => (
                <tr key={t.id ?? `tpl-${ti}`}>
                  <td>{t.id ?? '—'}</td>
                  <td>{t.min_score ?? '—'}</td>
                  <td>{t.max_score ?? '—'}</td>
                  <td style={{ maxWidth: 420, whiteSpace: 'pre-wrap' }}>{t.template_text ?? ''}</td>
                  <td>{t.is_active ? 'Yes' : 'No'}</td>
                  <td className="d-flex gap-1">
                    <button type="button" className="btn btn-sm btn-warning" onClick={() => openModal(t)}>
                      Edit
                    </button>
                    <button type="button" className="btn btn-sm btn-danger" onClick={() => onDelete(t.id)}>
                      Delete
                    </button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {modal ? (
        <div className="modal show d-block" tabIndex={-1} style={{ background: 'rgba(0,0,0,0.4)' }}>
          <div className="modal-dialog">
            <form className="modal-content" onSubmit={onSave}>
              <div className="modal-header">
                <h5 className="modal-title">{modal.id ? 'Edit Template' : 'New Template'}</h5>
                <button type="button" className="btn-close" aria-label="Close" onClick={() => setModal(null)} />
              </div>
              <div className="modal-body">
                <input type="hidden" name="id" value={modal.id ?? ''} />
                <div className="mb-3">
                  <label className="form-label">Min Score</label>
                  <input
                    type="number"
                    name="min_score"
                    className="form-control"
                    required
                    defaultValue={modal.min_score ?? ''}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label">Max Score</label>
                  <input
                    type="number"
                    name="max_score"
                    className="form-control"
                    required
                    defaultValue={modal.max_score ?? ''}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label">Template Text</label>
                  <textarea
                    name="template_text"
                    className="form-control"
                    required
                    rows={4}
                    defaultValue={modal.template_text ?? ''}
                  />
                </div>
                <div className="form-check mb-3">
                  <input
                    className="form-check-input"
                    type="checkbox"
                    name="is_active"
                    id="is_active"
                    defaultChecked={Boolean(modal.is_active)}
                  />
                  <label className="form-check-label" htmlFor="is_active">
                    Active
                  </label>
                </div>
              </div>
              <div className="modal-footer">
                <button type="button" className="btn btn-secondary" onClick={() => setModal(null)}>
                  Cancel
                </button>
                <button type="submit" className="btn btn-primary">
                  Save
                </button>
              </div>
            </form>
          </div>
        </div>
      ) : null}
    </div>
  )
}
