'use client';

import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useMemo, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { DmIcon } from '@/features/data-model/ui/icons';
import { cn } from '@/lib/utils/cn';
import { OsDropdown } from './object-settings/primitives';

/**
 * Settings › Customize Sales Extension Views
 * Design: settings-sales-extension-views.php?tab=email
 */

const OBJECTS = [
  { key: 'contacts', label: 'Contacts', icon: 'id-card' as const },
  { key: 'companies', label: 'Companies', icon: 'building' as const },
  { key: 'deals', label: 'Deals', icon: 'handshake' as const },
] as const;

type ObjectKey = (typeof OBJECTS)[number]['key'];
type TabKey = 'email' | 'prospecting';

type TeamView = {
  id: string;
  name: string;
  assignedTo: string;
  updatedAt: string;
  pinned?: boolean;
};

const SEED: TeamView[] = [
  {
    id: 'default',
    name: 'Default view',
    assignedTo: 'All unassigned teams and users',
    updatedAt: 'Sep 19, 2026 10:08 AM GMT+5:30',
    pinned: true,
  },
];

function hrefFor(object: ObjectKey, tab: TabKey) {
  return `/settings/sales-extension-views?object=${object}&tab=${tab}`;
}

export function SalesExtensionViewsView() {
  const toast = useToast();
  const params = useSearchParams();
  const objectParam = params.get('object') ?? 'contacts';
  const tabParam = params.get('tab') ?? 'email';

  const object: ObjectKey = OBJECTS.some((o) => o.key === objectParam)
    ? (objectParam as ObjectKey)
    : 'contacts';
  const tab: TabKey = tabParam === 'prospecting' ? 'prospecting' : 'email';
  const current = OBJECTS.find((o) => o.key === object) ?? OBJECTS[0];

  const [query, setQuery] = useState('');
  const [views, setViews] = useState<TeamView[]>(SEED);
  const [modalOpen, setModalOpen] = useState(false);
  const [viewName, setViewName] = useState('');
  const [assignTo, setAssignTo] = useState('All unassigned teams and users');
  const [objectSearch, setObjectSearch] = useState('');

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    if (!q) return views;
    return views.filter((v) => v.name.toLowerCase().includes(q));
  }, [query, views]);

  const objectOptions = OBJECTS.filter((o) =>
    o.label.toLowerCase().includes(objectSearch.trim().toLowerCase()),
  );

  const createView = () => {
    const name = viewName.trim();
    if (!name) return;
    setViews((cur) => [
      ...cur,
      {
        id: `v-${Date.now()}`,
        name,
        assignedTo: assignTo,
        updatedAt: new Date().toLocaleString(undefined, {
          dateStyle: 'medium',
          timeStyle: 'short',
        }),
      },
    ]);
    setModalOpen(false);
    setViewName('');
    setAssignTo('All unassigned teams and users');
    toast('Team view created', 'success');
  };

  return (
    <div className="os">
      <Link href="/settings/profile#tab-email" className="set-back-link">
        <CrmIcon name="chevron-left" className="iconSize-14" />
        <span>Email settings</span>
      </Link>

      <header className="set-head">
        <div>
          <h1 className="set-head__title">Customize Sales Extension Views</h1>
          <p className="set-head__sub">
            Configure the card layout for each object type and location in your CRM Sales Extension
            sidebar.
          </p>
        </div>
      </header>

      <div className="os-picker os-picker--plain">
        <span className="os-picker__label">Select an object:</span>
        <OsDropdown
          className="os-select"
          menuClassName="os-pop os-pop--objects"
          width={260}
          label={
            <>
              <span className="os-select__value">
                <DmIcon name={current.icon} size={16} />
                {current.label}
              </span>
              <DmIcon name="caret" size={18} />
            </>
          }
        >
          {(close) => (
            <>
              <label className="os-pop__search">
                <input
                  type="search"
                  placeholder="Search"
                  aria-label="Search objects"
                  value={objectSearch}
                  autoFocus
                  onChange={(e) => setObjectSearch(e.target.value)}
                />
                <DmIcon name="search" size={16} />
              </label>
              <div className="os-pop__list" role="listbox" aria-label="Objects">
                {objectOptions.map((o) => (
                  <Link
                    key={o.key}
                    role="option"
                    aria-selected={o.key === current.key}
                    className={cn('os-opt', o.key === current.key && 'is-selected')}
                    href={hrefFor(o.key, tab)}
                    onClick={() => {
                      setObjectSearch('');
                      close();
                    }}
                  >
                    <DmIcon name={o.icon} size={16} />
                    {o.label}
                  </Link>
                ))}
                {!objectOptions.length ? <p className="os-pop__empty">No objects found</p> : null}
              </div>
            </>
          )}
        </OsDropdown>
      </div>

      <div className="os-tabbar crm-mb-4">
        <nav className="os-tabs" aria-label="Extension view locations">
          <Link
            className={cn('os-tab', tab === 'email' && 'is-active')}
            href={hrefFor(object, 'email')}
            aria-current={tab === 'email' ? 'page' : undefined}
          >
            Email
          </Link>
          <Link
            className={cn('os-tab', tab === 'prospecting' && 'is-active')}
            href={hrefFor(object, 'prospecting')}
            aria-current={tab === 'prospecting' ? 'page' : undefined}
          >
            Prospecting
          </Link>
        </nav>
      </div>

      <div role="tabpanel">
        <div className="sev-alert" role="note">
          The &quot;Tasks&quot; card is fixed in position and always appears at the bottom of the
          card list.
        </div>

        <div className="os-toolbar">
          <label className="os-search">
            <input
              type="search"
              placeholder="Search by view name"
              aria-label="Search by view name"
              value={query}
              onChange={(e) => setQuery(e.target.value)}
            />
            <CrmIcon name="search" className="iconSize-16" />
          </label>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            onClick={() => setModalOpen(true)}
          >
            Create team view
          </button>
        </div>

        <div className="os-table-wrap">
          <table className="os-table">
            <thead>
              <tr>
                <th className="os-table__check">
                  <span className="check">
                    <input type="checkbox" aria-label="Select all views" disabled />
                    <span className="check__box" aria-hidden="true" />
                  </span>
                </th>
                <th>View name</th>
                <th>Assigned to</th>
                <th>Last updated</th>
                <th className="os-table__actions">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((view) => (
                <tr key={view.id}>
                  <td className="os-table__check">
                    <span className="check">
                      <input
                        type="checkbox"
                        aria-label={`Select ${view.name}`}
                        disabled={view.pinned}
                      />
                      <span className="check__box" aria-hidden="true" />
                    </span>
                  </td>
                  <td>
                    <span className="os-viewname">
                      {view.pinned ? (
                        <span className="os-viewname__icon">
                          <CrmIcon name="map-pin" className="iconSize-14" />
                        </span>
                      ) : null}
                      <button type="button" className="os-link link">
                        {view.name}
                      </button>
                    </span>
                  </td>
                  <td>{view.assignedTo}</td>
                  <td>{view.updatedAt}</td>
                  <td className="os-table__actions">
                    <button
                      type="button"
                      className="os-dots"
                      disabled={view.pinned}
                      aria-label={
                        view.pinned
                          ? "Default view can't be edited or deleted"
                          : `Actions for ${view.name}`
                      }
                      title={
                        view.pinned ? "The default view can't be edited or deleted" : undefined
                      }
                      onClick={() => {
                        if (view.pinned) return;
                        setViews((cur) => cur.filter((v) => v.id !== view.id));
                        toast('View removed', 'info');
                      }}
                    >
                      <CrmIcon name="menu" className="iconSize-16" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {filtered.length === 0 ? (
            <p className="os-noresults">No views match your search.</p>
          ) : null}
        </div>

        <nav className="os-pager" aria-label="Pagination">
          <span className="os-pager__step is-off">
            <CrmIcon name="chevron-left" className="iconSize-14" />
            Prev
          </span>
          <span className="os-pager__num" aria-current="page">
            1
          </span>
          <span className="os-pager__step is-off">
            Next
            <CrmIcon name="chevron-right" className="iconSize-14" />
          </span>
        </nav>
      </div>

      {modalOpen ? (
        <div className="os-modal">
          <div
            className="os-modal__box"
            role="dialog"
            aria-modal="true"
            aria-labelledby="sev-modal-title"
          >
            <div className="os-modal__head">
              <h2 id="sev-modal-title">Create team view</h2>
              <button
                type="button"
                className="os-x"
                aria-label="Close"
                onClick={() => setModalOpen(false)}
              >
                <CrmIcon name="x" className="iconSize-18" />
              </button>
            </div>
            <div className="os-modal__body">
              <label className="os-field">
                <span>View name *</span>
                <input
                  className="input"
                  type="text"
                  maxLength={60}
                  autoComplete="off"
                  value={viewName}
                  onChange={(e) => setViewName(e.target.value)}
                />
              </label>
              <label className="os-field">
                <span>Assign to</span>
                <select
                  className="input"
                  value={assignTo}
                  onChange={(e) => setAssignTo(e.target.value)}
                >
                  <option>All unassigned teams and users</option>
                  <option>Sales</option>
                  <option>Marketing</option>
                  <option>Customer Success</option>
                </select>
              </label>
            </div>
            <div className="os-modal__foot">
              <button
                type="button"
                className="btn-crm btn-crm--primary btn-crm--sm"
                disabled={!viewName.trim()}
                onClick={createView}
              >
                Create
              </button>
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                onClick={() => setModalOpen(false)}
              >
                Cancel
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}
