'use client';

import { useCallback } from 'react';
import { App, Input } from 'antd';
import { ApiError } from '../../lib/api';
import { customersApi, notifyCustomersChanged, type CustomerDeleteCheck } from '../../lib/customers';

function plural(n: number, word: string) {
  return `${n} ${word}${n === 1 ? '' : 's'}`;
}

function DeleteSummary({ name, check, onType }: { name: string; check: CustomerDeleteCheck; onType: (value: string) => void }) {
  const { contacts, notes, tasks, files } = check.willDelete;
  const parts = [contacts && plural(contacts, 'contact'), notes && plural(notes, 'note'), tasks && plural(tasks, 'task'), files && plural(files, 'file')].filter(Boolean);
  return (
    <div className="space-y-3 text-[13px]">
      <p className="m-0">{parts.length ? `This will also delete ${parts.join(', ')}.` : 'This customer has no contacts, notes, tasks or files.'} Converted leads stay, but lose their link to this customer. This cannot be undone.</p>
      <div>
        <label htmlFor="confirm-customer-name" className="mb-1 block text-[12.5px] text-[var(--tcx-muted)]">
          Type <b className="text-[var(--tcx-text)]">{name}</b> to confirm
        </label>
        <Input id="confirm-customer-name" autoComplete="off" onChange={(e) => onType(e.target.value)} />
      </div>
    </div>
  );
}

/** Smart customer delete: explains what blocks it, or lists what goes with it and asks for the name to be typed. */
export function useDeleteCustomer() {
  const { modal, message } = App.useApp();

  return useCallback(
    async (customer: { id: string; name: string }): Promise<boolean> => {
      let check: CustomerDeleteCheck;
      try {
        check = await customersApi.deleteCheck(customer.id);
      } catch (err) {
        message.error(err instanceof ApiError ? err.message : 'The customer could not be checked for deletion.');
        return false;
      }

      if (!check.canDelete) {
        modal.info({ title: `"${customer.name}" can't be deleted yet`, content: check.reason, okText: 'OK' });
        return false;
      }

      return new Promise<boolean>((resolve) => {
        const dialog = modal.confirm({
          title: `Delete "${customer.name}"?`,
          content: <DeleteSummary name={customer.name} check={check} onType={(value) => dialog.update({ okButtonProps: { danger: true, disabled: value.trim() !== customer.name.trim() } })} />,
          okText: 'Delete customer',
          okButtonProps: { danger: true, disabled: true },
          cancelText: 'Cancel',
          onCancel: () => resolve(false),
          onOk: async () => {
            try {
              await customersApi.remove(customer.id);
              notifyCustomersChanged();
              message.success('Customer deleted');
              resolve(true);
            } catch (err) {
              message.error(err instanceof ApiError ? err.message : 'The customer could not be deleted.');
              resolve(false);
            }
          },
        });
      });
    },
    [message, modal],
  );
}

export const useDeleteAccount = useDeleteCustomer;

/** Normalizes a website field to an http/https URL, returning null for unsafe schemes. */
export function safeWebsiteHref(raw: string | null | undefined): string | null {
  const trimmed = raw?.trim();
  if (!trimmed) return null;
  const candidate = /^https?:\/\//i.test(trimmed) ? trimmed : trimmed.includes('://') ? trimmed : `https://${trimmed}`;
  try {
    const parsed = new URL(candidate);
    if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
      return parsed.toString();
    }
  } catch {
    return null;
  }
  return null;
}

export function displayWebsiteHost(raw: string | null | undefined): string {
  const href = safeWebsiteHref(raw);
  if (!href) return raw?.trim() || '—';
  return href.replace(/^https?:\/\/(www\.)?/i, '').replace(/\/$/, '');
}
