import { useState, useEffect, useRef, useCallback } from 'react';
import { Modal } from '../../components/Modal';
import {
  useCreateCompany,
  useUpdateCompany,
  useIndustries,
  useAccountTypes,
  useTenantUsers,
  useSetCustomFieldValues,
} from '../hooks';
import { CustomFieldsForm } from '../CustomFieldsForm';
import type { Company, CustomFieldValue } from '../types';

interface CompanyFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  company?: Company | null;
  onSuccess: () => void;
}

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 selectStyle: React.CSSProperties = {
  ...inputStyle,
  cursor: 'pointer',
};

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

export function CompanyFormModal({
  isOpen,
  onClose,
  company,
  onSuccess,
}: CompanyFormModalProps) {
  const isEditMode = !!company;
  const createMutation = useCreateCompany();
  const updateMutation = useUpdateCompany();
  const setCustomFieldValues = useSetCustomFieldValues();
  const mutation = isEditMode ? updateMutation : createMutation;

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

  // Dropdown data
  const { data: industriesData } = useIndustries();
  const { data: accountTypesData } = useAccountTypes();
  const { data: usersData } = useTenantUsers();

  const industries = industriesData?.data ?? [];
  const accountTypes = accountTypesData?.data ?? [];
  const tenantUsers = usersData?.data ?? [];

  const [error, setError] = useState('');
  const [name, setName] = useState('');
  const [industryId, setIndustryId] = useState('');
  const [accountTypeId, setAccountTypeId] = useState('');
  const [ownerId, setOwnerId] = useState('');
  const [email, setEmail] = useState('');
  const [phone, setPhone] = 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('');

  useEffect(() => {
    if (isOpen) {
      setError('');
      if (company) {
        setName(company.name);
        setIndustryId(company.industryId ?? '');
        setAccountTypeId(company.accountTypeId ?? '');
        setOwnerId(company.ownerId ?? '');
        setEmail(company.email ?? '');
        setPhone(company.phone ?? '');
        setWebsite(company.website ?? '');
        setStreet(company.street ?? '');
        setZip(company.zip ?? '');
        setCity(company.city ?? '');
        setCountry(company.country ?? 'DE');
        setNotes(company.notes ?? '');
        setTagsInput(company.tags?.join(', ') ?? '');
      } else {
        setName('');
        setIndustryId('');
        setAccountTypeId('');
        setOwnerId('');
        setEmail('');
        setPhone('');
        setWebsite('');
        setStreet('');
        setZip('');
        setCity('');
        setCountry('DE');
        setNotes('');
        setTagsInput('');
      }
    }
  }, [isOpen, company]);

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

    if (!name.trim()) {
      setError('Name ist ein Pflichtfeld');
      return;
    }

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

    // Resolve ownerName from selected ownerId
    const selectedUser = ownerId
      ? tenantUsers.find((u) => u.id === ownerId)
      : null;
    const ownerName = selectedUser
      ? [selectedUser.firstName, selectedUser.lastName].filter(Boolean).join(' ') || selectedUser.email
      : undefined;

    const payload = {
      name: name.trim(),
      ...(industryId ? { industryId } : {}),
      ...(accountTypeId ? { accountTypeId } : {}),
      ...(ownerId ? { ownerId, ownerName } : {}),
      ...(email ? { email } : {}),
      ...(phone ? { phone } : {}),
      ...(website ? { website } : {}),
      ...(street ? { street } : {}),
      ...(zip ? { zip } : {}),
      ...(city ? { city } : {}),
      country,
      ...(notes ? { notes } : {}),
      ...(tags.length > 0 ? { tags } : {}),
    };

    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 && company) {
      updateMutation.mutate(
        { id: company.id, data: payload },
        {
          onSuccess: () => {
            saveCustomFields(company.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);
        },
      });
    }
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title={isEditMode ? 'Unternehmen bearbeiten' : 'Neues Unternehmen'}
      maxWidth="600px"
    >
      <form onSubmit={handleSubmit}>
        {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>
        )}

        {/* Name + Branche */}
        <div style={{ ...rowStyle, marginBottom: '1rem' }}>
          <div>
            <label style={labelStyle}>Name *</label>
            <input
              style={inputStyle}
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Firmenname"
              required
            />
          </div>
          <div>
            <label style={labelStyle}>Branche</label>
            <select
              style={selectStyle}
              value={industryId}
              onChange={(e) => setIndustryId(e.target.value)}
            >
              <option value="">— Keine —</option>
              {industries.map((ind) => (
                <option key={ind.id} value={ind.id}>
                  {ind.name}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Kontotyp + Zuständigkeit */}
        <div style={{ ...rowStyle, marginBottom: '1rem' }}>
          <div>
            <label style={labelStyle}>Kontotyp</label>
            <select
              style={selectStyle}
              value={accountTypeId}
              onChange={(e) => setAccountTypeId(e.target.value)}
            >
              <option value="">— Keine —</option>
              {accountTypes.map((at) => (
                <option key={at.id} value={at.id}>
                  {at.name}
                </option>
              ))}
            </select>
          </div>
          <div>
            <label style={labelStyle}>Zuständigkeit</label>
            <select
              style={selectStyle}
              value={ownerId}
              onChange={(e) => setOwnerId(e.target.value)}
            >
              <option value="">— Kein Owner —</option>
              {tenantUsers.map((u) => {
                const label = [u.firstName, u.lastName].filter(Boolean).join(' ') || u.email;
                return (
                  <option key={u.id} value={u.id}>
                    {label}
                  </option>
                );
              })}
            </select>
          </div>
        </div>

        {/* E-Mail + Telefon */}
        <div style={{ ...rowStyle, marginBottom: '1rem' }}>
          <div>
            <label style={labelStyle}>E-Mail</label>
            <input
              type="email"
              style={inputStyle}
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="info@firma.de"
            />
          </div>
          <div>
            <label style={labelStyle}>Telefon</label>
            <input
              style={inputStyle}
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="+49 ..."
            />
          </div>
        </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 */}
        <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 style={{ maxWidth: 120 }}>
            <label style={labelStyle}>PLZ</label>
            <input
              style={inputStyle}
              value={zip}
              onChange={(e) => setZip(e.target.value)}
            />
          </div>
          <div style={{ flex: 1 }}>
            <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, maxWidth: 120 }}
            value={country}
            onChange={(e) => setCountry(e.target.value)}
            maxLength={2}
            placeholder="DE"
          />
        </div>

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

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

        {/* Custom Fields */}
        {customFields.length > 0 && (
          <div style={{ marginBottom: '1rem' }}>
            <CustomFieldsForm
              fields={customFields}
              onChange={handleCustomFieldsChange}
            />
          </div>
        )}

        {/* Buttons */}
        <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"
            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>
      </form>
    </Modal>
  );
}
