'use client';

import { useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { cn } from '@/lib/utils/cn';

const SAMPLE = ['+91 93402-41931'];

export function BlockedNumbersView() {
  const toast = useToast();
  const [numbers, setNumbers] = useState<string[]>(SAMPLE);
  const [sortAsc, setSortAsc] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [raw, setRaw] = useState('');
  const [error, setError] = useState<string | null>(null);

  const sorted = useMemo(() => {
    const copy = [...numbers];
    copy.sort((a, b) => (sortAsc ? a.localeCompare(b) : b.localeCompare(a)));
    return copy;
  }, [numbers, sortAsc]);

  const addNumbers = () => {
    const parts = raw
      .split(/[,;\n]+/)
      .map((s) => s.trim())
      .filter(Boolean);
    if (!parts.length) {
      setError('Enter at least one phone number with a country code.');
      return;
    }
    if (parts.length > 50) {
      setError('You can add up to 50 numbers at a time.');
      return;
    }
    const invalid = parts.find((p) => !/^\+?[\d\s().-]{7,}$/.test(p));
    if (invalid) {
      setError(`“${invalid}” does not look like a valid phone number.`);
      return;
    }
    const next = [...numbers];
    let added = 0;
    for (const p of parts) {
      if (!next.some((n) => n.replace(/\s/g, '') === p.replace(/\s/g, ''))) {
        next.push(p);
        added += 1;
      }
    }
    setNumbers(next);
    setRaw('');
    setError(null);
    setModalOpen(false);
    toast(
      added ? `${added} number${added === 1 ? '' : 's'} blocked` : 'No new numbers to add',
      'success',
    );
  };

  return (
    <div className="calling-tool-page">
      <main className="calling-tool-main">
        <header className="set-head calling-tool-head">
          <h1 className="set-head__title">Blocked Numbers List</h1>
        </header>
        <p className="calling-tool-description">
          Manage which phone numbers are blocked for inbound and outbound calling. Changes could
          take up to five minutes to take effect.
          <br />
          Blocked numbers list does not include any national Do Not Call registries.
        </p>

        <div className="blocked-toolbar">
          <button
            type="button"
            className="blocked-add-btn add-number-button"
            onClick={() => {
              setError(null);
              setRaw('');
              setModalOpen(true);
            }}
          >
            Add numbers
          </button>
        </div>

        <div className="blocked-numbers-table-card">
          {sorted.length ? (
            <table className="blocked-numbers-table">
              <thead>
                <tr>
                  <th
                    scope="col"
                    className="blocked-th-sort"
                    tabIndex={0}
                    role="button"
                    aria-label="Sort by phone number"
                    onClick={() => setSortAsc((v) => !v)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        setSortAsc((v) => !v);
                      }
                    }}
                  >
                    <span className="blocked-th-sort__inner">
                      <span>Phone Number</span>
                      <span className="blocked-sort-arrows" aria-hidden>
                        ↑↓
                      </span>
                    </span>
                  </th>
                  <th scope="col" className="blocked-th-actions">
                    <span className="sr-only">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {sorted.map((n) => (
                  <tr className="blocked-number-row" key={n} data-number={n}>
                    <td className="blocked-number-cell">{n}</td>
                    <td className="blocked-action-cell">
                      <button
                        type="button"
                        className="blocked-remove-btn"
                        aria-label={`Remove ${n}`}
                        onClick={() => {
                          setNumbers((prev) => prev.filter((x) => x !== n));
                          toast('Number removed from block list', 'success');
                        }}
                      >
                        Remove
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <div className="blocked-empty-state">
              <p>No phone numbers are currently blocked.</p>
            </div>
          )}
        </div>
      </main>

      {modalOpen ? (
        <div className="add-numbers-modal-backdrop" onClick={() => setModalOpen(false)}>
          <div
            className="add-numbers-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="addNumbersTitle"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="add-numbers-modal__header">
              <h2 className="add-numbers-modal__title" id="addNumbersTitle">
                Add numbers
              </h2>
              <button
                type="button"
                className="add-numbers-modal__close"
                aria-label="Close"
                onClick={() => setModalOpen(false)}
              >
                ×
              </button>
            </div>
            <div className="add-numbers-modal__body">
              <p className="add-numbers-desc">Always block calls to and from these numbers.</p>
              <div className="add-numbers-field">
                <label htmlFor="blockedPhoneNumbers" className="add-numbers-label">
                  Phone numbers
                </label>
                <p className="add-numbers-subtext">
                  Separate numbers with commas. Include the country code, like +1-XXX-XXX-XXXX. You
                  can add up to 50 numbers at a time.
                </p>
                <textarea
                  id="blockedPhoneNumbers"
                  className="add-numbers-textarea"
                  rows={4}
                  value={raw}
                  onChange={(e) => setRaw(e.target.value)}
                />
                {error ? (
                  <p className={cn('add-numbers-error')} style={{ display: 'block' }}>
                    {error}
                  </p>
                ) : null}
              </div>
              <div className="add-numbers-modal__actions">
                <button
                  type="button"
                  className="add-numbers-btn add-numbers-btn--primary"
                  onClick={addNumbers}
                >
                  Add
                </button>
                <button
                  type="button"
                  className="add-numbers-btn add-numbers-btn--cancel"
                  onClick={() => setModalOpen(false)}
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}
