import { useState, useEffect, useRef, useCallback } from 'react';
import { Drawer } from '../../components/Drawer';
import { useCreateContact, useUpdateContact, useSetCustomFieldValues } from '../hooks';
import { companiesApi } from '../api';
import { CustomFieldsForm } from '../CustomFieldsForm';
import type {
  Contact,
  ContactType,
  ContactSource,
  EntityStatus,
  Company,
  CustomFieldValue,
} from '../types';
import { CONTACT_SOURCE_LABELS, ENTITY_STATUS_LABELS } from '../types';

interface ContactFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  contact?: Contact | null;
  onSuccess: () => void;
}

type FormTab = 'general' | 'details';

const FORM_ID = 'contact-form-drawer';

const labelStyle: React.CSSProperties = {
  fontSize: '0.875rem',
  fontWeight: 500,
  color: 'var(--color-text)',
  marginBottom: '0.25rem',
  display: 'block',
};

const inputStyle: React.CSSProperties = {
  width: '100%',
  padding: '0.625rem 0.75rem',
  border: '1px solid var(--color-border)',
  borderRadius: 'var(--radius-sm)',
  fontSize: '0.9375rem',
  outline: 'none',
  boxSizing: 'border-box',
  background: 'var(--color-bg-card)',
  color: 'var(--color-text)',
};

const rowStyle: React.CSSProperties = {
  display: 'grid',
  gridTemplateColumns: '1fr 1fr',
  gap: '0.75rem',
};

const sectionLabelStyle: React.CSSProperties = {
  fontSize: '0.75rem',
  fontWeight: 600,
  textTransform: 'uppercase',
  letterSpacing: '0.05em',
  color: 'var(--color-text-muted)',
  margin: '1.5rem 0 0.75rem',
  paddingBottom: '0.5rem',
  borderBottom: '1px solid var(--color-border)',
  display: 'block',
};

export function ContactFormModal({
  isOpen,
  onClose,
  contact,
  onSuccess,
}: ContactFormModalProps) {
  const isEditMode = !!contact;
  const createMutation = useCreateContact();
  const updateMutation = useUpdateContact();
  const setCustomFieldValues = useSetCustomFieldValues();
  const mutation = isEditMode ? updateMutation : createMutation;

  const [error, setError] = useState('');
  const [activeTab, setActiveTab] = useState<FormTab>('general');

  const customFieldValuesRef = useRef<
    Record<string, string | number | boolean | string[] | null>
  >({});
  const customFields: CustomFieldValue[] = contact?.customFields ?? [];
  const handleCustomFieldsChange = useCallback(
    (values: Record<string, string | number | boolean | string[] | null>) => {
      customFieldValuesRef.current = values;
    },
    [],
  );

  // type is preserved internally for existing ORGANIZATION contacts,
  // but new contacts always default to PERSON (no UI selector)
  const [type, setType] = useState<ContactType>('PERSON');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [companyName, setCompanyName] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [mobile, setMobile] = useState('');
  const [website, setWebsite] = useState('');
  const [street, setStreet] = useState('');
  const [zip, setZip] = useState('');
  const [city, setCity] = useState('');
  const [country, setCountry] = useState('DE');
  const [notes, setNotes] = useState('');
  const [tagsInput, setTagsInput] = useState('');
  const [position, setPosition] = useState('');
  const [linkedinUrl, setLinkedinUrl] = useState('');
  const [birthday, setBirthday] = useState('');
  const [source, setSource] = useState<ContactSource | ''>('');
  const [department, setDepartment] = useState('');
  const [status, setStatus] = useState<EntityStatus>('ACTIVE');
  // When a company is linked, the address can be inherited from it
  const [useCompanyAddress, setUseCompanyAddress] = useState(false);

  // Company autocomplete
  const [companySearch, setCompanySearch] = useState('');
  const [companyResults, setCompanyResults] = useState<Company[]>([]);
  const [selectedCompany, setSelectedCompany] = useState<{
    id: string;
    name: string;
  } | null>(null);
  const [showCompanyDropdown, setShowCompanyDropdown] = useState(false);
  const companyRef = useRef<HTMLDivElement>(null);
  const companySearchTimeout = useRef<ReturnType<typeof setTimeout>>();

  // Click-outside for company dropdown
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (
        companyRef.current &&
        !companyRef.current.contains(e.target as Node)
      ) {
        setShowCompanyDropdown(false);
      }
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  // Company search (debounced)
  useEffect(() => {
    if (companySearchTimeout.current) clearTimeout(companySearchTimeout.current);
    if (!companySearch || companySearch.length < 2) {
      setCompanyResults([]);
      return;
    }
    companySearchTimeout.current = setTimeout(async () => {
      try {
        const res = await companiesApi.list({
          search: companySearch,
          pageSize: 8,
        });
        setCompanyResults(res.data);
        setShowCompanyDropdown(true);
      } catch {
        setCompanyResults([]);
      }
    }, 300);
    return () => {
      if (companySearchTimeout.current) clearTimeout(companySearchTimeout.current);
    };
  }, [companySearch]);

  // Initialise form when drawer opens
  useEffect(() => {
    if (isOpen) {
      setError('');
      setActiveTab('general');
      if (contact) {
        setType(contact.type);
        setFirstName(contact.firstName ?? '');
        setLastName(contact.lastName ?? '');
        setCompanyName(contact.companyName ?? '');
        setEmail(contact.email ?? '');
        setPhone(contact.phone ?? '');
        setMobile(contact.mobile ?? '');
        setWebsite(contact.website ?? '');
        setStreet(contact.street ?? '');
        setZip(contact.zip ?? '');
        setCity(contact.city ?? '');
        setCountry(contact.country ?? 'DE');
        setNotes(contact.notes ?? '');
        setTagsInput((contact.tags ?? []).join(', '));
        setPosition(contact.position ?? '');
        setLinkedinUrl(contact.linkedinUrl ?? '');
        setBirthday(
          contact.birthday ? contact.birthday.split('T')[0] : '',
        );
        setSource((contact.source as ContactSource) ?? '');
        setDepartment(contact.department ?? '');
        setStatus(contact.status ?? 'ACTIVE');
        if (contact.company) {
          setSelectedCompany({
            id: contact.company.id,
            name: contact.company.name,
          });
          setCompanySearch(contact.company.name);
          // Default: use company address when contact has no own address
          setUseCompanyAddress(!contact.street);
        } else {
          setSelectedCompany(null);
          setCompanySearch('');
          setUseCompanyAddress(false);
        }
      } else {
        setType('PERSON');
        setFirstName('');
        setLastName('');
        setCompanyName('');
        setEmail('');
        setPhone('');
        setMobile('');
        setWebsite('');
        setStreet('');
        setZip('');
        setCity('');
        setCountry('DE');
        setNotes('');
        setTagsInput('');
        setPosition('');
        setLinkedinUrl('');
        setBirthday('');
        setSource('');
        setDepartment('');
        setStatus('ACTIVE');
        setSelectedCompany(null);
        setCompanySearch('');
        setUseCompanyAddress(true); // default: inherit from company once one is selected
      }
      setCompanyResults([]);
      setShowCompanyDropdown(false);
    }
  }, [isOpen, contact]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    const tags = tagsInput
      .split(',')
      .map((t) => t.trim())
      .filter(Boolean);

    // Only include address when not inheriting from company
    const addressPayload =
      !selectedCompany || !useCompanyAddress
        ? {
            ...(street ? { street } : {}),
            ...(zip ? { zip } : {}),
            ...(city ? { city } : {}),
            country,
          }
        : {};

    const payload = {
      type,
      ...(type === 'PERSON' ? { firstName, lastName } : { companyName }),
      ...(email ? { email } : {}),
      ...(phone ? { phone } : {}),
      ...(mobile ? { mobile } : {}),
      ...(website ? { website } : {}),
      ...(linkedinUrl ? { linkedinUrl } : {}),
      ...(birthday ? { birthday: new Date(birthday).toISOString() } : {}),
      ...(source ? { source } : {}),
      ...(department ? { department } : {}),
      status,
      ...addressPayload,
      ...(notes ? { notes } : {}),
      ...(tags.length > 0 ? { tags } : {}),
      ...(selectedCompany ? { companyId: selectedCompany.id } : {}),
      ...(position ? { position } : {}),
    };

    const saveCustomFields = (entityId: string) => {
      const vals = customFieldValuesRef.current;
      const entries = Object.entries(vals);
      if (entries.length === 0) return;
      setCustomFieldValues.mutate({
        entityId,
        data: {
          values: entries.map(([fieldDefId, value]) => ({
            fieldDefId,
            value,
          })),
        },
      });
    };

    if (isEditMode && contact) {
      updateMutation.mutate(
        { id: contact.id, data: payload },
        {
          onSuccess: () => {
            saveCustomFields(contact.id);
            onSuccess();
          },
          onError: (err: unknown) => {
            const msg =
              (
                err as {
                  response?: { data?: { error?: { message?: string } } };
                }
              )?.response?.data?.error?.message ?? 'Fehler beim Speichern';
            setError(msg);
          },
        },
      );
    } else {
      createMutation.mutate(payload, {
        onSuccess: (res) => {
          if (res?.data?.id) saveCustomFields(res.data.id);
          onSuccess();
        },
        onError: (err: unknown) => {
          const msg =
            (
              err as {
                response?: { data?: { error?: { message?: string } } };
              }
            )?.response?.data?.error?.message ?? 'Fehler beim Anlegen';
          setError(msg);
        },
      });
    }
  };

  const tabBtnStyle = (tab: FormTab): React.CSSProperties => ({
    padding: '0.5rem 1.25rem',
    background: 'none',
    border: 'none',
    borderBottom: `2px solid ${activeTab === tab ? 'var(--color-primary)' : 'transparent'}`,
    cursor: 'pointer',
    fontSize: '0.9375rem',
    fontWeight: activeTab === tab ? 600 : 400,
    color:
      activeTab === tab
        ? 'var(--color-primary)'
        : 'var(--color-text-secondary)',
    marginBottom: '-1px',
    transition: 'color 0.15s, border-color 0.15s',
    whiteSpace: 'nowrap',
  });

  const drawerFooter = (
    <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.75rem' }}>
      <button
        type="button"
        onClick={onClose}
        disabled={mutation.isPending}
        style={{
          padding: '0.5rem 1rem',
          background: 'transparent',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-sm)',
          fontSize: '0.875rem',
          cursor: 'pointer',
          color: 'var(--color-text-secondary)',
        }}
      >
        Abbrechen
      </button>
      <button
        type="submit"
        form={FORM_ID}
        disabled={mutation.isPending}
        style={{
          padding: '0.5rem 1rem',
          background: 'var(--color-primary)',
          color: 'white',
          border: 'none',
          borderRadius: 'var(--radius-sm)',
          fontSize: '0.875rem',
          fontWeight: 600,
          cursor: mutation.isPending ? 'wait' : 'pointer',
          opacity: mutation.isPending ? 0.7 : 1,
        }}
      >
        {mutation.isPending
          ? 'Speichern...'
          : isEditMode
            ? 'Speichern'
            : 'Anlegen'}
      </button>
    </div>
  );

  return (
    <Drawer
      isOpen={isOpen}
      onClose={onClose}
      title={isEditMode ? 'Kontakt bearbeiten' : 'Neuer Kontakt'}
      width="540px"
      footer={drawerFooter}
    >
      {/* Error banner */}
      {error && (
        <div
          style={{
            padding: '0.75rem',
            background: '#fef2f2',
            border: '1px solid #fecaca',
            borderRadius: 'var(--radius-sm)',
            color: 'var(--color-error)',
            fontSize: '0.875rem',
            marginBottom: '1rem',
          }}
        >
          {error}
        </div>
      )}

      {/* Tab navigation */}
      <div
        style={{
          display: 'flex',
          borderBottom: '1px solid var(--color-border)',
          marginBottom: '1.5rem',
        }}
      >
        <button
          type="button"
          style={tabBtnStyle('general')}
          onClick={() => setActiveTab('general')}
        >
          Allgemein
        </button>
        <button
          type="button"
          style={tabBtnStyle('details')}
          onClick={() => setActiveTab('details')}
        >
          Details &amp; Adresse
        </button>
      </div>

      <form id={FORM_ID} onSubmit={handleSubmit}>
        {/* ── TAB 1: Allgemein ───────────────────────────────────── */}
        {activeTab === 'general' && (
          <>
            {/* Name */}
            {type === 'PERSON' ? (
              <div style={{ ...rowStyle, marginBottom: '1rem' }}>
                <div>
                  <label style={labelStyle}>Vorname</label>
                  <input
                    style={inputStyle}
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                    placeholder="Max"
                  />
                </div>
                <div>
                  <label style={labelStyle}>Nachname</label>
                  <input
                    style={inputStyle}
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                    placeholder="Mustermann"
                  />
                </div>
              </div>
            ) : (
              <div style={{ marginBottom: '1rem' }}>
                <label style={labelStyle}>Firmenname</label>
                <input
                  style={inputStyle}
                  value={companyName}
                  onChange={(e) => setCompanyName(e.target.value)}
                  placeholder="Muster GmbH"
                />
              </div>
            )}

            {/* Company autocomplete */}
            <div
              style={{ marginBottom: '1rem', position: 'relative' }}
              ref={companyRef}
            >
              <label style={labelStyle}>Unternehmen</label>
              <input
                style={inputStyle}
                value={companySearch}
                onChange={(e) => {
                  setCompanySearch(e.target.value);
                  if (selectedCompany) {
                    setSelectedCompany(null);
                    setUseCompanyAddress(false);
                  }
                }}
                onFocus={() => {
                  if (companyResults.length > 0) setShowCompanyDropdown(true);
                }}
                placeholder="Unternehmen suchen…"
              />
              {selectedCompany && (
                <button
                  type="button"
                  onClick={() => {
                    setSelectedCompany(null);
                    setCompanySearch('');
                    setUseCompanyAddress(false);
                  }}
                  style={{
                    position: 'absolute',
                    right: 8,
                    top: 30,
                    background: 'none',
                    border: 'none',
                    color: 'var(--color-text-muted)',
                    cursor: 'pointer',
                    fontSize: '1rem',
                  }}
                >
                  ×
                </button>
              )}
              {showCompanyDropdown && companyResults.length > 0 && (
                <div
                  style={{
                    position: 'absolute',
                    top: '100%',
                    left: 0,
                    right: 0,
                    background: 'var(--color-bg-card)',
                    border: '1px solid var(--color-border)',
                    borderRadius: 'var(--radius-sm)',
                    boxShadow: 'var(--shadow-md)',
                    zIndex: 10,
                    maxHeight: 200,
                    overflowY: 'auto',
                  }}
                >
                  {companyResults.map((comp) => (
                    <div
                      key={comp.id}
                      onClick={() => {
                        setSelectedCompany({ id: comp.id, name: comp.name });
                        setCompanySearch(comp.name);
                        setShowCompanyDropdown(false);
                        setUseCompanyAddress(true); // default: inherit address
                      }}
                      style={{
                        padding: '0.5rem 0.75rem',
                        cursor: 'pointer',
                        fontSize: '0.875rem',
                        borderBottom: '1px solid var(--color-border)',
                      }}
                      onMouseEnter={(e) =>
                        (
                          (e.currentTarget as HTMLDivElement).style.background =
                            'var(--color-bg)'
                        )
                      }
                      onMouseLeave={(e) =>
                        (
                          (e.currentTarget as HTMLDivElement).style.background =
                            'transparent'
                        )
                      }
                    >
                      {comp.name}
                      {comp.industry && (
                        <span
                          style={{
                            color: 'var(--color-text-muted)',
                            marginLeft: '0.5rem',
                            fontSize: '0.8125rem',
                          }}
                        >
                          {comp.industry}
                        </span>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* Position + Abteilung (PERSON only) */}
            {type === 'PERSON' && (
              <div style={{ ...rowStyle, marginBottom: '1rem' }}>
                <div>
                  <label style={labelStyle}>Position</label>
                  <input
                    style={inputStyle}
                    value={position}
                    onChange={(e) => setPosition(e.target.value)}
                    placeholder="z.B. Geschäftsführer"
                  />
                </div>
                <div>
                  <label style={labelStyle}>Abteilung</label>
                  <input
                    style={inputStyle}
                    value={department}
                    onChange={(e) => setDepartment(e.target.value)}
                    placeholder="z.B. Einkauf"
                  />
                </div>
              </div>
            )}

            {/* E-Mail */}
            <div style={{ marginBottom: '1rem' }}>
              <label style={labelStyle}>E-Mail</label>
              <input
                type="email"
                style={inputStyle}
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="mail@example.com"
              />
            </div>

            {/* Telefon + Mobil */}
            <div style={{ ...rowStyle, marginBottom: '1rem' }}>
              <div>
                <label style={labelStyle}>Telefon</label>
                <input
                  style={inputStyle}
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  placeholder="+49 …"
                />
              </div>
              <div>
                <label style={labelStyle}>Mobil</label>
                <input
                  style={inputStyle}
                  value={mobile}
                  onChange={(e) => setMobile(e.target.value)}
                  placeholder="+49 …"
                />
              </div>
            </div>

            {/* LinkedIn */}
            <div style={{ marginBottom: '1rem' }}>
              <label style={labelStyle}>LinkedIn</label>
              <input
                style={inputStyle}
                value={linkedinUrl}
                onChange={(e) => setLinkedinUrl(e.target.value)}
                placeholder="https://linkedin.com/in/…"
              />
            </div>
          </>
        )}

        {/* ── TAB 2: Details & Adresse ──────────────────────────── */}
        {activeTab === 'details' && (
          <>
            {/* Geburtsdatum + Quelle */}
            <div style={{ ...rowStyle, marginBottom: '1rem' }}>
              {type === 'PERSON' && (
                <div>
                  <label style={labelStyle}>Geburtsdatum</label>
                  <input
                    type="date"
                    style={inputStyle}
                    value={birthday}
                    onChange={(e) => setBirthday(e.target.value)}
                  />
                </div>
              )}
              <div>
                <label style={labelStyle}>Quelle</label>
                <select
                  style={{ ...inputStyle, cursor: 'pointer' }}
                  value={source}
                  onChange={(e) => setSource(e.target.value as ContactSource)}
                >
                  <option value="">-- Keine --</option>
                  {Object.entries(CONTACT_SOURCE_LABELS).map(([val, label]) => (
                    <option key={val} value={val}>
                      {label}
                    </option>
                  ))}
                </select>
              </div>
            </div>

            {/* Status */}
            <div style={{ marginBottom: '1rem' }}>
              <label style={labelStyle}>Status</label>
              <select
                style={{ ...inputStyle, cursor: 'pointer' }}
                value={status}
                onChange={(e) => setStatus(e.target.value as EntityStatus)}
              >
                {Object.entries(ENTITY_STATUS_LABELS).map(([val, label]) => (
                  <option key={val} value={val}>
                    {label}
                  </option>
                ))}
              </select>
            </div>

            {/* Website */}
            <div style={{ marginBottom: '1rem' }}>
              <label style={labelStyle}>Website</label>
              <input
                style={inputStyle}
                value={website}
                onChange={(e) => setWebsite(e.target.value)}
                placeholder="https://…"
              />
            </div>

            {/* ── Adresse ── */}
            <span style={sectionLabelStyle}>Adresse</span>

            {/* "Adresse vom Unternehmen übernehmen" */}
            {selectedCompany && (
              <div style={{ marginBottom: '1rem' }}>
                <label
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '0.5rem',
                    cursor: 'pointer',
                    fontSize: '0.875rem',
                    color: 'var(--color-text)',
                  }}
                >
                  <input
                    type="checkbox"
                    checked={useCompanyAddress}
                    onChange={(e) => setUseCompanyAddress(e.target.checked)}
                    style={{ width: 15, height: 15, cursor: 'pointer' }}
                  />
                  Adresse vom Unternehmen übernehmen
                </label>
                {useCompanyAddress && (
                  <p
                    style={{
                      fontSize: '0.8125rem',
                      color: 'var(--color-text-muted)',
                      marginTop: '0.375rem',
                      marginLeft: '1.5rem',
                      marginBottom: 0,
                    }}
                  >
                    Die Adresse wird aus „{selectedCompany.name}" übernommen.
                  </p>
                )}
              </div>
            )}

            {/* Address fields (hidden when using company address) */}
            {(!selectedCompany || !useCompanyAddress) && (
              <>
                <div style={{ marginBottom: '1rem' }}>
                  <label style={labelStyle}>Straße</label>
                  <input
                    style={inputStyle}
                    value={street}
                    onChange={(e) => setStreet(e.target.value)}
                  />
                </div>
                <div style={{ ...rowStyle, marginBottom: '1rem' }}>
                  <div>
                    <label style={labelStyle}>PLZ</label>
                    <input
                      style={inputStyle}
                      value={zip}
                      onChange={(e) => setZip(e.target.value)}
                    />
                  </div>
                  <div>
                    <label style={labelStyle}>Stadt</label>
                    <input
                      style={inputStyle}
                      value={city}
                      onChange={(e) => setCity(e.target.value)}
                    />
                  </div>
                </div>
                <div style={{ marginBottom: '1rem' }}>
                  <label style={labelStyle}>Land</label>
                  <input
                    style={inputStyle}
                    value={country}
                    onChange={(e) => setCountry(e.target.value)}
                    placeholder="DE"
                    maxLength={2}
                  />
                </div>
              </>
            )}

            {/* ── Notizen & Tags ── */}
            <span style={sectionLabelStyle}>Notizen &amp; Tags</span>

            <div style={{ marginBottom: '1rem' }}>
              <label style={labelStyle}>Notizen</label>
              <textarea
                style={{ ...inputStyle, minHeight: 80, resize: 'vertical' }}
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
              />
            </div>

            <div style={{ marginBottom: '1rem' }}>
              <label style={labelStyle}>Tags (kommasepariert)</label>
              <input
                style={inputStyle}
                value={tagsInput}
                onChange={(e) => setTagsInput(e.target.value)}
                placeholder="VIP, Neukunde, …"
              />
            </div>

            {/* Custom Fields */}
            {customFields.length > 0 && (
              <CustomFieldsForm
                fields={customFields}
                onChange={handleCustomFieldsChange}
              />
            )}
          </>
        )}
      </form>
    </Drawer>
  );
}
