'use client';

import { useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import { errorText } from '@/lib/api/errors';
import { createHoliday, deleteHoliday, listHolidays, type BusinessHoliday } from '../api.client';

/**
 * Account Defaults › Company holidays (QA 16 Oct #140): the calendar that business-day waits,
 * workflow delays and sequences with "Skip holidays" leave out. Everyone sees it; admins change
 * it. US federal holidays are always skipped as well.
 */
export function CompanyHolidaysPanel({ isAdmin }: { isAdmin: boolean }) {
  const toast = useToast();
  const thisYear = new Date().getFullYear();
  const [year, setYear] = useState(thisYear);
  const [rows, setRows] = useState<BusinessHoliday[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [date, setDate] = useState('');
  const [name, setName] = useState('');
  const [busy, setBusy] = useState(false);

  const load = useCallback(async () => {
    setError(null);
    try {
      setRows(await listHolidays(year));
    } catch (err) {
      setRows([]);
      setError(errorText(err));
    }
  }, [year]);

  useEffect(() => {
    void load();
  }, [load]);

  const add = async () => {
    if (!date || !name.trim() || busy) return;
    setBusy(true);
    setError(null);
    try {
      await createHoliday({ date, name: name.trim() });
      setDate('');
      setName('');
      toast('Holiday added.', 'success');
      if (Number(date.slice(0, 4)) !== year) setYear(Number(date.slice(0, 4)));
      else await load();
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  const remove = async (holiday: BusinessHoliday) => {
    if (busy) return;
    setBusy(true);
    try {
      await deleteHoliday(holiday.id);
      toast(`${holiday.name} removed.`, 'success');
      await load();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="set-stack">
      <p className="set-intro">
        Sequences with Skip holidays, business-day waits and workflow delays don&apos;t run steps on
        these days (US federal holidays are skipped too).
        {!isAdmin ? ' Only admins can change them.' : ''}
      </p>
      {error ? <Alert tone="danger">{error}</Alert> : null}
      <div className="set-block">
        <div className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-2">
          <h2 className="set-block__title crm-mb-0">Company holidays</h2>
          <div className="crm-d-flex crm-align-items-center crm-gap-2">
            <button
              type="button"
              className="btn-crm btn-crm--ghost btn-crm--sm"
              aria-label="Previous year"
              onClick={() => setYear((y) => y - 1)}
            >
              ‹
            </button>
            <strong>{year}</strong>
            <button
              type="button"
              className="btn-crm btn-crm--ghost btn-crm--sm"
              aria-label="Next year"
              onClick={() => setYear((y) => y + 1)}
            >
              ›
            </button>
          </div>
        </div>
        {rows === null ? (
          <p className="set-block__sub">Loading…</p>
        ) : rows.length === 0 ? (
          <p className="set-block__sub">No company holidays in {year}.</p>
        ) : (
          <ul className="set-holidays crm-mt-3 crm-mb-0 crm-d-grid crm-gap-2">
            {rows.map((h) => (
              <li
                key={h.id}
                className="crm-d-flex crm-align-items-center crm-justify-content-between crm-gap-2"
              >
                <span>
                  <strong>
                    {new Date(`${h.date}T12:00:00Z`).toLocaleDateString(undefined, {
                      weekday: 'short',
                      day: 'numeric',
                      month: 'short',
                      timeZone: 'UTC',
                    })}
                  </strong>{' '}
                  · {h.name}
                </span>
                {isAdmin ? (
                  <button
                    type="button"
                    className="btn-crm btn-crm--ghost btn-crm--sm"
                    disabled={busy}
                    onClick={() => void remove(h)}
                  >
                    Remove
                  </button>
                ) : null}
              </li>
            ))}
          </ul>
        )}
      </div>
      {isAdmin ? (
        <form
          className="set-block crm-d-flex crm-flex-wrap crm-align-items-end crm-gap-2"
          onSubmit={(e) => {
            e.preventDefault();
            void add();
          }}
        >
          <label className="field crm-mb-0">
            <span className="field__label">Date</span>
            <input
              className="input"
              type="date"
              value={date}
              required
              onChange={(e) => setDate(e.target.value)}
            />
          </label>
          <label className="field crm-mb-0">
            <span className="field__label">Name</span>
            <input
              className="input"
              value={name}
              maxLength={100}
              required
              placeholder="e.g. Diwali"
              onChange={(e) => setName(e.target.value)}
            />
          </label>
          <button
            type="submit"
            className="btn-crm btn-crm--primary"
            disabled={busy || !date || !name.trim()}
          >
            Add holiday
          </button>
        </form>
      ) : null}
    </div>
  );
}
