'use client';

import React from 'react';
import { Form, Input, Select } from 'antd';
import { type CustomerInput } from '../../lib/customers';
import type { DirectoryUser } from '../../lib/leads';
import { emailValidationRule, phoneValidationRule, websiteValidationRule } from '../../lib/validation';

/** Values held by the shared customer form (New customer, Edit customer and Convert lead). */
export interface CustomerFormValues {
  name: string;
  contactPerson: string;
  email?: string;
  contactTitle?: string;
  phone?: string;
  city?: string;
  industry?: string;
  website?: string;
  techStack?: string;
  ownerId?: string;
}

/** Turns form values into the API payload: trimmed text, empty optional fields as null. */
export function toCustomerInput(v: CustomerFormValues): CustomerInput {
  const text = (value?: string) => value?.trim() || null;
  return {
    name: v.name.trim(),
    contactPerson: v.contactPerson.trim(),
    email: text(v.email),
    contactTitle: text(v.contactTitle),
    phone: text(v.phone),
    city: text(v.city),
    industry: v.industry ?? null,
    website: text(v.website),
    techStack: text(v.techStack),
    ownerId: v.ownerId ?? null,
  };
}

/** Same modal width as the Lead form so all sales modals look alike. */
export const CUSTOMER_MODAL_WIDTH = 620;

/**
 * Customer fields shared by New customer, Edit customer and Convert lead, laid out like the Lead and Deal forms
 * (two columns, no section headings). Extra fields (such as the convert deal fields) render in the same grid via children.
 */
export function CustomerFormFields({ people, hideCompany = false, children }: { people: DirectoryUser[]; currentIndustry?: string | null; hideCompany?: boolean; children?: React.ReactNode }) {
  return (
    <div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
      {hideCompany ? null : (
        <Form.Item
          name="name"
          label="Customer / Company name"
          className="sm:col-span-2"
          rules={[
            { required: true, whitespace: true, message: 'Enter the company name' },
            { max: 255, message: 'Use 255 characters or fewer' },
          ]}
        >
          <Input placeholder="Enter company name" autoFocus />
        </Form.Item>
      )}
      <Form.Item
        name="contactPerson"
        label="Contact person"
        rules={[
          { required: true, whitespace: true, message: 'Enter the contact person' },
          { max: 200, message: 'Use 200 characters or fewer' },
        ]}
      >
        <Input placeholder="Enter contact person name" />
      </Form.Item>
      <Form.Item
        name="email"
        label="Email"
        dependencies={['phone']}
        validateTrigger={['onChange', 'onBlur']}
        rules={[
          ({ getFieldValue }) => ({
            validator(_, value) {
              const phoneVal = getFieldValue('phone');
              const hasEmail = Boolean(typeof value === 'string' ? value.trim() : value);
              const hasPhone = Boolean(typeof phoneVal === 'string' ? phoneVal.trim() : phoneVal);
              if (!hasEmail && !hasPhone) {
                return Promise.reject(new Error('Provide at least an Email or Phone'));
              }
              return Promise.resolve();
            },
          }),
          ...emailValidationRule(false),
        ]}
      >
        <Input placeholder="Enter email address" inputMode="email" />
      </Form.Item>
      <Form.Item name="contactTitle" label="Designation" rules={[{ max: 150, message: 'Use 150 characters or fewer' }]}>
        <Input placeholder="Enter designation or job title" />
      </Form.Item>
      {hideCompany ? null : (
        <>
          <Form.Item
            name="phone"
            label="Phone"
            dependencies={['email']}
            validateTrigger={['onChange', 'onBlur']}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  const emailVal = getFieldValue('email');
                  const hasEmail = Boolean(typeof emailVal === 'string' ? emailVal.trim() : emailVal);
                  const hasPhone = Boolean(typeof value === 'string' ? value.trim() : value);
                  if (!hasEmail && !hasPhone) {
                    return Promise.reject(new Error('Provide at least an Email or Phone'));
                  }
                  return Promise.resolve();
                },
              }),
              phoneValidationRule,
              { max: 50, message: 'Use 50 characters or fewer' },
            ]}
          >
            <Input placeholder="Enter phone number" inputMode="tel" />
          </Form.Item>
          <Form.Item name="industry" label="Industry" rules={[{ max: 100, message: 'Use 100 characters or fewer' }]}>
            <Input placeholder="Enter industry" />
          </Form.Item>
          <Form.Item name="city" label="City" rules={[{ max: 100, message: 'Use 100 characters or fewer' }]}>
            <Input placeholder="Enter city" />
          </Form.Item>
          <Form.Item name="website" label="Website" validateTrigger={['onChange', 'onBlur']} rules={[{ max: 255, message: 'Use 255 characters or fewer' }, websiteValidationRule]}>
            <Input placeholder="Enter website URL (e.g. https://example.com or example.com)" />
          </Form.Item>
          <Form.Item name="ownerId" label="Owner" rules={[{ required: true, message: 'Choose an owner' }]}>
            <Select showSearch optionFilterProp="label" placeholder="Assign owner" options={people.map((p) => ({ value: p.id, label: p.name }))} />
          </Form.Item>
        </>
      )}
      {children}
    </div>
  );
}
