'use client'

import { useState, useEffect } from 'react'
import { Star, X, Plus, Loader2 } from 'lucide-react'
import { Contact, CreateContactData, UpdateContactData } from '@/lib/api/contacts'
import { categoriesAPI, Category } from '@/lib/api/categories'
import { employeesAPI, Employee } from '@/lib/api/employees'
import CategorySelector from './CategorySelector'
import DuplicateAlert from './DuplicateAlert'

interface ContactFormProps {
  contact?: Contact
  onSubmit: (data: CreateContactData | UpdateContactData) => Promise<void>
  onCancel: () => void
  submitting?: boolean
}

const buildInitialFormData = (contact?: Contact): CreateContactData => ({
  type: contact?.type || 'INDIVIDUAL',
  name: contact?.name || '',
  nameAr: contact?.nameAr,
  email: contact?.email,
  phone: contact?.phone,
  mobile: contact?.mobile,
  website: contact?.website,
  companyName: contact?.companyName,
  companyNameAr: contact?.companyNameAr,
  taxNumber: contact?.taxNumber,
  commercialRegister: contact?.commercialRegister,
  address: contact?.address,
  city: contact?.city,
  country: contact?.country || 'Syria',
  postalCode: contact?.postalCode,
  source: contact?.source || 'WEBSITE',
  categories: contact?.categories?.map((c: any) => c.id || c) || [],
  tags: contact?.tags || [],
  parentId: contact?.parent?.id,
  employeeId: contact?.employeeId ?? undefined,
  customFields: contact?.customFields
})

export default function ContactForm({ contact, onSubmit, onCancel, submitting = false }: ContactFormProps) {
  const isEdit = !!contact

  const [formData, setFormData] = useState<CreateContactData>(buildInitialFormData(contact))
  const [rating, setRating] = useState<number>(contact?.rating || 0)
  const [newTag, setNewTag] = useState('')
  const [formErrors, setFormErrors] = useState<Record<string, string>>({})
  const [categories, setCategories] = useState<Category[]>([])
  const [employees, setEmployees] = useState<Employee[]>([])

  useEffect(() => {
    setFormData(buildInitialFormData(contact))
    setRating(contact?.rating || 0)
    setNewTag('')
    setFormErrors({})
  }, [contact])

  useEffect(() => {
    categoriesAPI.getTree().then(setCategories).catch(() => {})
  }, [])

  useEffect(() => {
    employeesAPI.getAll({ status: 'ACTIVE', pageSize: 500 }).then((r) => setEmployees(r.employees)).catch(() => {})
  }, [])

  const companyEmployeeCategoryId = (() => {
    const flatten = (cats: Category[]): Category[] => {
      const out: Category[] = []
      const walk = (c: Category) => {
        out.push(c)
        c.children?.forEach(walk)
      }
      cats.forEach(walk)
      return out
    }
    return flatten(categories).find((c) => c.name === 'Company Employee')?.id
  })()

  const isCompanyEmployeeSelected = companyEmployeeCategoryId && (formData.categories || []).includes(companyEmployeeCategoryId)

  const organizationTypes = new Set([
    'COMPANY',
    'HOLDING',
    'GOVERNMENT',
    'ORGANIZATION',
    'EMBASSIES',
    'BANK',
    'UNIVERSITY',
    'SCHOOL',
    'UN',
    'NGO',
    'INSTITUTION',
    'SUPPLIER',
  ])

  const isOrganizationType = organizationTypes.has(formData.type)
  const showCompanyFields = isOrganizationType

  const validateForm = (): boolean => {
    const errors: Record<string, string> = {}

    if (!formData.name || formData.name.trim().length < 2) {
      errors.name = 'Name must be at least 2 characters'
    }

    if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      errors.email = 'Invalid email format'
    }

    if (formData.phone && !/^\+?[\d\s-()]+$/.test(formData.phone)) {
      errors.phone = 'Invalid phone format'
    }

    if (!formData.type) {
      errors.type = 'Contact type is required'
    }

    if (!formData.source) {
      errors.source = 'Source is required'
    }

    setFormErrors(errors)
    return Object.keys(errors).length === 0
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!validateForm()) return
  const cleanData = Object.entries({ ...formData, rating }).reduce((acc, [key, value]) => {
  const requiredFields = ['type', 'name', 'source', 'country']

    // keep required fields as-is
    if (requiredFields.includes(key)) {
      acc[key] = value
      return acc
    }

    // in edit mode, allow clearing optional fields by sending null
    if (isEdit && value === '') {
      acc[key] = null
      return acc
    }

    // in create mode, ignore empty optional fields
    if (value !== '') {
      acc[key] = value
    }

    return acc
  }, {} as any)

    if (!cleanData.parentId) {
      delete cleanData.parentId
    }

    if (cleanData.categories && cleanData.categories.length === 0) {
      delete cleanData.categories
    }

    if (!cleanData.parentId) {
  delete cleanData.parentId
}

    if (cleanData.categories && cleanData.categories.length === 0) {
      delete cleanData.categories
    }

    // employeeId:
    // - in create: remove if empty
    // - in edit: keep null if user cleared it
    if (!isEdit && !cleanData.employeeId) {
      delete cleanData.employeeId
    }

    const submitData = isEdit
      ? cleanData as UpdateContactData
      : cleanData as CreateContactData

    await onSubmit(submitData)
  }

  const addTag = () => {
    if (newTag.trim() && !formData.tags?.includes(newTag.trim())) {
      setFormData({
        ...formData,
        tags: [...(formData.tags || []), newTag.trim()]
      })
      setNewTag('')
    }
  }

  const removeTag = (tagToRemove: string) => {
    setFormData({
      ...formData,
      tags: formData.tags?.filter(tag => tag !== tagToRemove) || []
    })
  }

  return (
    <form onSubmit={handleSubmit} noValidate className="space-y-6">
      <div>
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Basic Information</h3>
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Contact Type <span className="text-red-500">*</span>
              </label>
              <select
                value={formData.type}
                onChange={(e) => setFormData({ ...formData, type: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
              >
                <option value="INDIVIDUAL">Individual - فرد</option>
                <option value="COMPANY">Company - شركة</option>
                <option value="HOLDING">Holding - مجموعة</option>
                <option value="GOVERNMENT">Government - حكومي</option>
                <option value="ORGANIZATION">Organizations - منظمات</option>
                <option value="EMBASSIES">Embassies - سفارات</option>
                <option value="BANK">Banks - بنوك</option>
                <option value="UNIVERSITY">Universities - جامعات</option>
                <option value="SCHOOL">Schools - مدارس</option>
                <option value="UN">UN - الأمم المتحدة</option>
                <option value="NGO">NGO - منظمة غير حكومية</option>
                <option value="INSTITUTION">Institution - مؤسسة</option>
                <option value="SUPPLIER">Supplier - مورّد</option>
              </select>
              {formErrors.type && <p className="text-red-500 text-xs mt-1">{formErrors.type}</p>}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Source <span className="text-red-500">*</span>
              </label>
              <select
                value={formData.source}
                onChange={(e) => setFormData({ ...formData, source: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
              >
                <option value="WEBSITE">Website</option>
                <option value="REFERRAL">Referral</option>
                <option value="COLD_CALL">Cold Call</option>
                <option value="SOCIAL_MEDIA">Social Media</option>
                <option value="EXHIBITION">Exhibition</option>
                <option value="EVENT">Event</option>
                <option value="VISIT">Visit</option>
                <option value="OTHER">Other</option>
              </select>
              {formErrors.source && <p className="text-red-500 text-xs mt-1">{formErrors.source}</p>}
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              {isOrganizationType ? 'Contact Person Name' : 'Name'} <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
              placeholder={isOrganizationType ? 'Enter contact person name' : 'Enter contact name'}
            />
            {formErrors.name && <p className="text-red-500 text-xs mt-1">{formErrors.name}</p>}
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              Rating
            </label>
            <div className="flex items-center gap-2">
              {[1, 2, 3, 4, 5].map((star) => (
                <button
                  key={star}
                  type="button"
                  onClick={() => setRating(star)}
                  className="focus:outline-none transition-colors"
                >
                  <Star
                    className={`h-8 w-8 ${
                      star <= rating
                        ? 'fill-yellow-400 text-yellow-400'
                        : 'text-gray-300 hover:text-yellow-200'
                    }`}
                  />
                </button>
              ))}
              {rating > 0 && (
                <button
                  type="button"
                  onClick={() => setRating(0)}
                  className="ml-2 text-sm text-gray-500 hover:text-gray-700"
                >
                  Clear
                </button>
              )}
            </div>
          </div>
        </div>
      </div>

      <div className="pt-6 border-t">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Contact Methods</h3>
        <div className="space-y-4">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Email
              </label>
              <input
                type="email"
                value={formData.email || ''}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                placeholder="email@example.com"
              />
              {formErrors.email && <p className="text-red-500 text-xs mt-1">{formErrors.email}</p>}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Phone
              </label>
              <input
                type="tel"
                value={formData.phone || ''}
                onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                placeholder="+966 50 123 4567"
              />
              {formErrors.phone && <p className="text-red-500 text-xs mt-1">{formErrors.phone}</p>}
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Mobile
              </label>
              <input
                type="tel"
                value={formData.mobile || ''}
                onChange={(e) => setFormData({ ...formData, mobile: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                placeholder="+966 55 123 4567"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Website
              </label>
              <input
                type="text"
                value={formData.website || ''}
                onChange={(e) => setFormData({ ...formData, website: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                placeholder="www.example.com"
              />
            </div>
          </div>
        </div>
      </div>

      {showCompanyFields && (
        <div className="pt-6 border-t">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Company Information</h3>
          <div className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  {formData.type === 'EMBASSIES' ? 'Embassy Name' : 'Company / Organization Name'}
                </label>
                <input
                  type="text"
                  value={formData.companyName || ''}
                  onChange={(e) => setFormData({ ...formData, companyName: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                  placeholder={formData.type === 'EMBASSIES' ? 'Embassy name' : 'Company / organization name'}
                />
              </div>

            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Tax Number
                </label>
                <input
                  type="text"
                  value={formData.taxNumber || ''}
                  onChange={(e) => setFormData({ ...formData, taxNumber: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900 font-mono"
                  placeholder="Tax registration number"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Commercial Register
                </label>
                <input
                  type="text"
                  value={formData.commercialRegister || ''}
                  onChange={(e) => setFormData({ ...formData, commercialRegister: e.target.value })}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900 font-mono"
                  placeholder="Commercial register number"
                />
              </div>
            </div>
          </div>
        </div>
      )}

      <div className="pt-6 border-t">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Address Information</h3>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Street Address
            </label>
            <input
              type="text"
              value={formData.address || ''}
              onChange={(e) => setFormData({ ...formData, address: e.target.value })}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
              placeholder="Street address"
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                City
              </label>
              <input
                type="text"
                value={formData.city || ''}
                onChange={(e) => setFormData({ ...formData, city: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                placeholder="City"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Country
              </label>
              <input
                type="text"
                value={formData.country || ''}
                onChange={(e) => setFormData({ ...formData, country: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                placeholder="Country"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Postal Code
              </label>
              <input
                type="text"
                value={formData.postalCode || ''}
                onChange={(e) => setFormData({ ...formData, postalCode: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
                placeholder="Postal code"
              />
            </div>
          </div>
        </div>
      </div>

      <div className="pt-6 border-t">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Categories</h3>
        <CategorySelector
          selectedIds={formData.categories || []}
          onChange={(categories) => setFormData({ ...formData, categories })}
          multiSelect={true}
        />
      </div>

      {isCompanyEmployeeSelected && (
        <div className="pt-6 border-t">
          <h3 className="text-lg font-semibold text-gray-900 mb-4">Link to Employee (Optional)</h3>
          <p className="text-sm text-gray-600 mb-2">
            Link this contact to an HR employee record for sync and unified views.
          </p>
          <select
            value={formData.employeeId || ''}
            onChange={(e) => setFormData({ ...formData, employeeId: e.target.value || undefined })}
            className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
          >
            <option value="">None (No link)</option>
            {employees.map((emp) => (
              <option key={emp.id} value={emp.id}>
                {emp.firstName} {emp.lastName} ({emp.email}){emp.uniqueEmployeeId ? ` - ${emp.uniqueEmployeeId}` : ''}
              </option>
            ))}
          </select>
        </div>
      )}

      <div className="pt-6 border-t">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">Tags</h3>
        <div className="space-y-3">
          <div className="flex gap-2">
            <input
              type="text"
              value={newTag}
              onChange={(e) => setNewTag(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), addTag())}
              className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white text-gray-900"
              placeholder="Add a tag (press Enter)"
            />
            <button
              type="button"
              onClick={addTag}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
            >
              <Plus className="h-5 w-5" />
            </button>
          </div>

          {formData.tags && formData.tags.length > 0 && (
            <div className="flex flex-wrap gap-2">
              {formData.tags.map((tag, index) => (
                <span
                  key={index}
                  className="inline-flex items-center gap-2 px-3 py-1 bg-gray-100 text-gray-700 rounded-full text-sm"
                >
                  #{tag}
                  <button
                    type="button"
                    onClick={() => removeTag(tag)}
                    className="hover:text-red-600 transition-colors"
                  >
                    <X className="h-3 w-3" />
                  </button>
                </span>
              ))}
            </div>
          )}
        </div>
      </div>

      <DuplicateAlert
        email={formData.email}
        phone={formData.phone}
        mobile={formData.mobile}
        taxNumber={formData.taxNumber}
        commercialRegister={formData.commercialRegister}
        excludeId={contact?.id}
        onMerge={(contactId) => {
          if (typeof window !== 'undefined') {
            window.location.href = `/contacts/merge?sourceId=${contactId}`
          }
        }}
      />

      <div className="flex items-center justify-end gap-3 pt-6 border-t">
        <button
          type="button"
          onClick={onCancel}
          className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors"
          disabled={submitting}
        >
          Cancel
        </button>
        <button
          type="submit"
          className="flex items-center gap-2 px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          disabled={submitting}
        >
          {submitting ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              {isEdit ? 'Updating...' : 'Creating...'}
            </>
          ) : (
            <>
              {isEdit ? 'Update Contact' : 'Create Contact'}
            </>
          )}
        </button>
      </div>
    </form>
  )
}