'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import { apiGet, apiPost } from '@/lib/api/client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

type ObjectType = 'contact' | 'company';
type Issue = 'name' | 'phone' | 'email' | 'stale';

interface Summary {
  total: number;
  issues: Record<Issue, number>;
  duplicates: number;
}
interface IssueRow {
  id: string;
  name: string | null;
  field: string;
  value: string | null;
  suggestion: string | null;
}
interface Usage {
  field: string;
  label: string;
  filled: number;
  total: number;
  percent: number;
}

const ISSUES: Array<{ key: Issue; label: string; help: string; objects: ObjectType[] }> = [
  {
    key: 'name',
    label: 'Name formatting',
    help: 'Extra spaces, all lower or upper case',
    objects: ['contact', 'company'],
  },
  {
    key: 'phone',
    label: 'Phone formatting',
    help: 'Letters or characters a phone number does not have',
    objects: ['contact', 'company'],
  },
  {
    key: 'email',
    label: 'Email formatting',
    help: 'Capital letters or spaces',
    objects: ['contact'],
  },
  {
    key: 'stale',
    label: 'Stale records',
    help: 'Not changed for 180 days',
    objects: ['contact', 'company'],
  },
];

const FIELD_LABELS: Record<string, string> = {
  firstName: 'First name',
  lastName: 'Last name',
  name: 'Company name',
  phone: 'Phone number',
  email: 'Email',
  updatedAt: 'Last modified',
};

const PATHS: Record<ObjectType, string> = { contact: '/contacts', company: '/companies' };

/**
 * HUB-519: Data quality: formatting issues (names, phones, emails) with the suggested fix
 * applied to the picked records in bulk, stale records, how much each property is filled in,
 * and the duplicates overview (Manage duplicates).
 */
function DataQuality() {
  const params = useSearchParams();
  const router = useRouter();
  const toast = useToast();
  const objectType: ObjectType = params.get('object') === 'company' ? 'company' : 'contact';
  const [issue, setIssue] = useState<Issue>('name');
  const [summary, setSummary] = useState<Summary | null>(null);
  const [rows, setRows] = useState<IssueRow[] | null>(null);
  const [total, setTotal] = useState(0);
  const [usage, setUsage] = useState<Usage[] | null>(null);
  const [picked, setPicked] = useState<Set<string>>(new Set());
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const loadSummary = useCallback(() => {
    apiGet<Summary>('/data-quality/summary', { params: { objectType } }).then(
      setSummary,
      (err: unknown) => setError(errorText(err)),
    );
    apiGet<{ data: Usage[] }>('/data-quality/property-usage', { params: { objectType } }).then(
      (res) => setUsage(res.data),
      () => setUsage([]),
    );
  }, [objectType]);

  const loadIssues = useCallback(() => {
    setRows(null);
    setPicked(new Set());
    apiGet<{ data: IssueRow[]; total: number }>('/data-quality/issues', {
      params: { objectType, issue, limit: 200 },
    }).then(
      (res) => {
        setRows(res.data);
        setTotal(res.total);
      },
      (err: unknown) => {
        setRows([]);
        setError(errorText(err));
      },
    );
  }, [objectType, issue]);

  useEffect(() => {
    setSummary(null);
    setUsage(null);
    loadSummary();
  }, [loadSummary]);
  useEffect(() => {
    if (!ISSUES.find((i) => i.key === issue)?.objects.includes(objectType)) setIssue('name');
    else loadIssues();
  }, [loadIssues, issue, objectType]);

  const ids = [...new Set((rows ?? []).map((r) => r.id))];
  const fix = async () => {
    setBusy(true);
    try {
      const res = await apiPost<{ fixed: number; skipped: Array<{ id: string; reason: string }> }>(
        '/data-quality/fix',
        { objectType, issue, recordIds: [...picked] },
      );
      toast(
        `${res.fixed} fixed${res.skipped.length ? `, ${res.skipped.length} skipped` : ''}`,
        res.skipped.length ? 'info' : 'success',
      );
      loadSummary();
      loadIssues();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  const fixable = issue !== 'stale';
  return (
    <div className="tools-page contacts-page companies-page">
      <div className="page-header">
        <div className="page-title">
          <h1>Data quality</h1>
        </div>
        <div className="actions">
          <Link className="btn-crm btn-crm--outline" href={`${PATHS[objectType]}/duplicates`}>
            Manage duplicates
          </Link>
        </div>
      </div>
      <nav className="tools-tabs" aria-label="Objects">
        {(['contact', 'company'] as const).map((o) => (
          <button
            key={o}
            type="button"
            className={cn('tools-tab', o === objectType && 'is-active')}
            onClick={() => router.replace(`/data-quality?object=${o}`)}
          >
            {o === 'contact' ? 'Contacts' : 'Companies'}
          </button>
        ))}
      </nav>
      {error ? <Alert tone="danger">{error}</Alert> : null}

      <div className="dq-cards">
        {ISSUES.filter((i) => i.objects.includes(objectType)).map((i) => (
          <button
            key={i.key}
            type="button"
            className={cn('dq-card', issue === i.key && 'is-active')}
            onClick={() => setIssue(i.key)}
          >
            <strong>{summary ? summary.issues[i.key].toLocaleString() : '…'}</strong>
            <span>{i.label}</span>
            <span>{i.help}</span>
          </button>
        ))}
        <Link className="dq-card" href={`${PATHS[objectType]}/duplicates`}>
          <strong>{summary ? summary.duplicates.toLocaleString() : '…'}</strong>
          <span>Possible duplicates</span>
          <span>Review and merge</span>
        </Link>
      </div>

      <section className="crm-table-card companies-table-card">
        <div className="crm-d-flex crm-align-items-center crm-gap-2 crm-p-3">
          <strong className="crm-fs-6">
            {ISSUES.find((i) => i.key === issue)?.label} ({total.toLocaleString()})
          </strong>
          {fixable ? (
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm crm-ms-auto"
              disabled={busy || picked.size === 0}
              onClick={() => void fix()}
            >
              Fix {picked.size || ''} selected
            </button>
          ) : null}
        </div>
        {rows === null ? (
          <div className="companies-empty">
            <p>Loading…</p>
          </div>
        ) : rows.length === 0 ? (
          <div className="companies-empty">
            <h3>Nothing to fix</h3>
            <p>No records have this issue.</p>
          </div>
        ) : (
          <div className="crm-table-wrap">
            <table className="crm-table">
              <thead>
                <tr>
                  {fixable ? (
                    <th className="companies-check-cell">
                      <label className="check">
                        <input
                          type="checkbox"
                          aria-label="Select all"
                          checked={picked.size > 0 && picked.size === ids.length}
                          onChange={() =>
                            setPicked(picked.size === ids.length ? new Set() : new Set(ids))
                          }
                        />
                        <span className="check__box" aria-hidden />
                      </label>
                    </th>
                  ) : null}
                  <th>Record</th>
                  <th>Property</th>
                  <th>Current value</th>
                  {fixable ? <th>Suggested fix</th> : null}
                </tr>
              </thead>
              <tbody>
                {rows.map((r) => (
                  <tr key={`${r.id}-${r.field}`}>
                    {fixable ? (
                      <td>
                        <label className="check">
                          <input
                            type="checkbox"
                            aria-label={`Select ${r.name ?? 'record'}`}
                            checked={picked.has(r.id)}
                            onChange={() =>
                              setPicked((cur) => {
                                const next = new Set(cur);
                                if (next.has(r.id)) next.delete(r.id);
                                else next.add(r.id);
                                return next;
                              })
                            }
                          />
                          <span className="check__box" aria-hidden />
                        </label>
                      </td>
                    ) : null}
                    <td>
                      <Link className="link" href={`${PATHS[objectType]}/${r.id}`}>
                        {r.name || 'Untitled'}
                      </Link>
                    </td>
                    <td>{FIELD_LABELS[r.field] ?? r.field}</td>
                    <td>
                      {r.field === 'updatedAt' && r.value
                        ? new Date(r.value).toLocaleDateString()
                        : (r.value ?? '--')}
                    </td>
                    {fixable ? <td>{r.suggestion ?? '--'}</td> : null}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      <section className="crm-table-card companies-table-card">
        <div className="crm-p-3">
          <strong className="crm-fs-6">Property usage</strong>
          <p className="crm-fs-8 crm-text-muted crm-mb-0">
            How many {objectType === 'contact' ? 'contacts' : 'companies'} have each property filled
            in, least used first.
          </p>
        </div>
        {usage === null ? (
          <div className="companies-empty">
            <p>Loading…</p>
          </div>
        ) : (
          <div className="crm-table-wrap">
            <table className="crm-table">
              <thead>
                <tr>
                  <th>Property</th>
                  <th>Filled in</th>
                  <th>Fill rate</th>
                </tr>
              </thead>
              <tbody>
                {usage.map((u) => (
                  <tr key={u.field}>
                    <td>{u.label}</td>
                    <td>
                      {u.filled.toLocaleString()} of {u.total.toLocaleString()}
                    </td>
                    <td>
                      <span className="crm-d-flex crm-align-items-center crm-gap-2">
                        <span className="dq-bar" aria-hidden>
                          <span style={{ width: `${u.percent}%` }} />
                        </span>
                        {u.percent}%
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  );
}

export function DataQualityView() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <DataQuality />
    </Suspense>
  );
}
