import { type FormEvent, useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import {
  fetchWhatsappManageLinks,
  saveWhatsappLink,
  sendWhatsappInvites,
  type WhatsappSectionRow,
} from '../../api/whatsapp'

function linkForSection(
  linksBySection: Record<string, { invite_link?: string | null; active?: number | boolean }> | undefined,
  sid: number,
) {
  if (!linksBySection) return undefined
  return linksBySection[String(sid)] ?? linksBySection[sid]
}

export function WhatsappManageLinksPage() {
  const [payload, setPayload] = useState<Awaited<ReturnType<typeof fetchWhatsappManageLinks>> | null>(null)
  const [error, setError] = useState<string | null>(null)
  const [message, setMessage] = useState<string | null>(null)
  const [inviteMode, setInviteMode] = useState<'all' | 'class' | 'parents'>('all')
  const [inviteClassId, setInviteClassId] = useState<number | ''>('')
  const [inviteParentIds, setInviteParentIds] = useState<number[]>([])

  useEffect(() => {
    let cancelled = false
    ;(async () => {
      try {
        const data = await fetchWhatsappManageLinks()
        if (cancelled) return
        setPayload(data)
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load WhatsApp settings.')
      }
    })()
    return () => {
      cancelled = true
    }
  }, [])

  const sections = payload?.sections ?? []
  const linksBySection = payload?.linksBySection as
    | Record<string, { invite_link?: string | null; active?: number | boolean }>
    | undefined
  const parents = payload?.parents ?? []

  const parentOptions = useMemo(
    () =>
      parents.map((p) => {
        let label = `${p.lastname ?? ''}, ${p.firstname ?? ''}`.trim()
        if (p.email) label += ` — ${p.email}`
        label += p.source === 'parents' ? ' (Second Parent)' : ' (Primary)'
        return { id: p.id, label }
      }),
    [parents],
  )

  async function onSaveSection(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const fd = new FormData(e.currentTarget)
    const class_section_id = Number(fd.get('class_section_id'))
    const class_section_name = String(fd.get('class_section_name') ?? '')
    const invite_link = String(fd.get('invite_link') ?? '')
    const active = fd.get('active') === 'on'
    try {
      await saveWhatsappLink({ class_section_id, class_section_name, invite_link, active })
      setMessage('Link saved.')
      const data = await fetchWhatsappManageLinks()
      setPayload(data)
    } catch (err) {
      setMessage(err instanceof Error ? err.message : 'Save failed.')
    }
  }

  async function onSendInvites(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    try {
      const body: {
        mode: 'all' | 'class' | 'parents'
        class_section_id?: number | null
        parent_ids?: number[]
      } = { mode: inviteMode }
      if (inviteMode === 'class') {
        body.class_section_id = inviteClassId === '' ? null : Number(inviteClassId)
      }
      if (inviteMode === 'parents') {
        body.parent_ids = inviteParentIds
      }
      await sendWhatsappInvites(body)
      setMessage('Invite request submitted.')
    } catch (err) {
      setMessage(err instanceof Error ? err.message : 'Send failed.')
    }
  }

  const schoolYear = payload?.schoolYear ?? ''
  const semester = payload?.semester ?? ''

  return (
    <div className="container my-4">
      <style>{`
        #parentPicker .form-select[multiple] {
          height: clamp(420px, 65vh, 820px);
          min-height: 420px;
        }
        #parentPicker .form-select[multiple] option {
          font-size: 0.95rem;
          line-height: 1.25;
        }
      `}</style>
      <h2 className="mb-3">WhatsApp Group Links</h2>
      {message ? <div className="alert alert-info py-2">{message}</div> : null}
      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="card-header d-flex justify-content-between align-items-center px-0 border-0 mb-3">
        <Link className="btn btn-outline-secondary btn-sm" to="/app/whatsapp/parent-contacts-by-class">
          <i className="bi bi-people" /> Parent Contacts by Class
        </Link>
      </div>

      <div className="row g-4">
        <div className="col-lg-7">
          <div className="card">
            <div className="card-header">
              Set / Update Links ({schoolYear}
              {semester ? ` - ${semester}` : ''})
            </div>
            <div className="card-body">
              {sections.length === 0 ? (
                <p className="text-muted">No sections found for this term.</p>
              ) : (
                sections.map((sec: WhatsappSectionRow) => {
                  const sid = Number(sec.class_section_id ?? sec.id ?? 0)
                  const sname = sec.class_section_name ?? sec.name ?? `Section ${sid}`
                  const existing = linkForSection(linksBySection, sid)
                  return (
                    <form
                      key={sid}
                      className="row gy-2 align-items-end border-bottom pb-3 mb-3"
                      onSubmit={(e) => void onSaveSection(e)}
                    >
                      <input type="hidden" name="class_section_id" value={sid} />
                      <div className="col-12">
                        <label className="form-label">Class / Section</label>
                        <input type="text" className="form-control" name="class_section_name" value={sname} readOnly />
                      </div>
                      <div className="col-12">
                        <label className="form-label">Invite Link</label>
                        <input
                          type="url"
                          className="form-control"
                          name="invite_link"
                          placeholder="https://chat.whatsapp.com/..."
                          defaultValue={existing?.invite_link ?? ''}
                          required
                        />
                        {existing?.invite_link ? (
                          <small className="text-success d-block mt-1">Link set.</small>
                        ) : (
                          <small className="text-muted d-block mt-1">No link set yet.</small>
                        )}
                      </div>
                      <div className="col-md-6">
                        <div className="form-check mt-2">
                          <input
                            className="form-check-input"
                            type="checkbox"
                            name="active"
                            id={`active-${sid}`}
                            defaultChecked={Boolean(existing?.active === 1 || existing?.active === true)}
                          />
                          <label className="form-check-label" htmlFor={`active-${sid}`}>
                            Active
                          </label>
                        </div>
                      </div>
                      <div className="col-md-6 text-end">
                        <button type="submit" className="btn btn-primary">
                          Save
                        </button>
                      </div>
                    </form>
                  )
                })
              )}
            </div>
          </div>
        </div>

        <div className="col-lg-5">
          <div className="card">
            <div className="card-header">Send Invites</div>
            <div className="card-body">
              <form id="sendInvitesForm" onSubmit={(e) => void onSendInvites(e)}>
                <div className="mb-3">
                  <label className="form-label">Mode</label>
                  <select
                    className="form-select"
                    value={inviteMode}
                    onChange={(e) => setInviteMode(e.target.value as 'all' | 'class' | 'parents')}
                    required
                  >
                    <option value="all">All parents</option>
                    <option value="class">Parents in a class</option>
                    <option value="parents">Specific parent(s)</option>
                  </select>
                </div>

                <div className={`mb-3 ${inviteMode === 'class' ? '' : 'd-none'}`}>
                  <label className="form-label">Class / Section</label>
                  <select
                    className="form-select"
                    value={inviteClassId === '' ? '' : String(inviteClassId)}
                    onChange={(e) =>
                      setInviteClassId(e.target.value ? Number(e.target.value) : '')
                    }
                    required={inviteMode === 'class'}
                  >
                    <option value="">-- Select Class / Section --</option>
                    {sections.map((s: WhatsappSectionRow) => {
                      const cid = Number(s.class_section_id ?? s.id)
                      const hasLink = Boolean(linkForSection(linksBySection, cid)?.invite_link)
                      return (
                        <option key={cid} value={cid}>
                          {s.class_section_name}
                          {hasLink ? ' (has link)' : ''}
                        </option>
                      )
                    })}
                  </select>
                </div>

                <div className={`mb-3 ${inviteMode === 'parents' ? '' : 'd-none'}`} id="parentPicker">
                  <label className="form-label">Parents</label>
                  <select
                    className="form-select"
                    multiple
                    size={25}
                    value={inviteParentIds.map(String)}
                    onChange={(e) => {
                      const selected = Array.from(e.target.selectedOptions).map((o) => Number(o.value))
                      setInviteParentIds(selected)
                    }}
                    required={inviteMode === 'parents'}
                  >
                    {parentOptions.length === 0 ? (
                      <option disabled>No parents available</option>
                    ) : (
                      parentOptions.map((p) => (
                        <option key={p.id} value={p.id}>
                          {p.label}
                        </option>
                      ))
                    )}
                  </select>
                  <small className="text-muted">Hold Ctrl/Cmd to select multiple.</small>
                </div>

                <div className="text-end">
                  <button type="submit" className="btn btn-success">
                    Send Emails
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
