import React, { useEffect, useState } from 'react';
import { apiClient } from '../../services/apiClient';
import { Building2, Loader2 } from 'lucide-react';

type CompanySettings = {
  name: string;
  fullName?: string | null;
  address?: string | null;
  phone?: string | null;
  email?: string | null;
  website?: string | null;
  licenseNumber?: string | null;
  licenseValidUntil?: string | null;
  logoUrl?: string | null;
};

const emptyCompany: CompanySettings = {
  name: '',
  fullName: '',
  address: '',
  phone: '',
  email: '',
  website: '',
  licenseNumber: '',
  licenseValidUntil: '',
  logoUrl: '',
};

export const CompanySection: React.FC = () => {
  const [form, setForm] = useState<CompanySettings>(emptyCompany);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);

  const load = async () => {
    try {
      setIsLoading(true);
      const data = await apiClient.get<any>('/settings/company');
      setForm({
        name: data.name || '',
        fullName: data.fullName ?? '',
        address: data.address ?? '',
        phone: data.phone ?? '',
        email: data.email ?? '',
        website: data.website ?? '',
        licenseNumber: data.licenseNumber ?? '',
        licenseValidUntil: data.licenseValidUntil
          ? String(data.licenseValidUntil).substring(0, 10)
          : '',
        logoUrl: data.logoUrl ?? '',
      });
    } catch (err) {
      console.error('Error loading company settings:', err);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    load();
  }, []);

  const handleChange = (field: keyof CompanySettings, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

  const handleSave = async () => {
    if (!form.name) return;
    try {
      setIsSaving(true);
      await apiClient.put('/settings/company', {
        name: form.name,
        fullName: form.fullName || null,
        address: form.address || null,
        phone: form.phone || null,
        email: form.email || null,
        website: form.website || null,
        licenseNumber: form.licenseNumber || null,
        licenseValidUntil: form.licenseValidUntil || null,
        logoUrl: form.logoUrl || null,
      });
      alert('Данные управляющей компании сохранены');
    } catch (err: any) {
      console.error('Error saving company settings:', err);
      alert(`Не удалось сохранить: ${err?.message || 'Неизвестная ошибка'}`);
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-primary-600" />
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center gap-3 mb-6">
        <div className="w-10 h-10 rounded-xl bg-primary-50 flex items-center justify-center">
          <Building2 className="w-5 h-5 text-primary-600" />
        </div>
        <div>
          <h3 className="text-lg font-bold text-slate-800">Управляющая компания</h3>
          <p className="text-xs text-slate-500">
            Эти данные сохраняются в базе и подставляются в отчеты жителям и PR-отчеты
          </p>
        </div>
      </div>

      <div className="space-y-4 max-w-2xl">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Краткое наименование
            </label>
            <input
              type="text"
              value={form.name}
              onChange={(e) => handleChange('name', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
              placeholder='Например: УК "Дружба"'
            />
          </div>
          <div>
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Полное наименование
            </label>
            <input
              type="text"
              value={form.fullName || ''}
              onChange={(e) => handleChange('fullName', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
              placeholder='Например: ООО "Управляющая компания Дружба"'
            />
          </div>
          <div className="md:col-span-2">
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Адрес
            </label>
            <input
              type="text"
              value={form.address || ''}
              onChange={(e) => handleChange('address', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
              placeholder="Юридический / фактический адрес"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Телефон
            </label>
            <input
              type="text"
              value={form.phone || ''}
              onChange={(e) => handleChange('phone', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
              placeholder="+7 (___) ___-__-__"
            />
          </div>
          <div>
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Email
            </label>
            <input
              type="email"
              value={form.email || ''}
              onChange={(e) => handleChange('email', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
              placeholder="info@company.ru"
            />
          </div>
          <div>
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Сайт
            </label>
            <input
              type="text"
              value={form.website || ''}
              onChange={(e) => handleChange('website', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
              placeholder="https://..."
            />
          </div>
          <div>
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Номер лицензии
            </label>
            <input
              type="text"
              value={form.licenseNumber || ''}
              onChange={(e) => handleChange('licenseNumber', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
              placeholder="Лицензия №..."
            />
          </div>
          <div>
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Лицензия действительна до
            </label>
            <input
              type="date"
              value={form.licenseValidUntil || ''}
              onChange={(e) => handleChange('licenseValidUntil', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
            />
          </div>
          <div>
            <label className="block text-xs font-black text-slate-500 uppercase mb-1">
              Логотип (URL)
            </label>
            <input
              type="text"
              value={form.logoUrl || ''}
              onChange={(e) => handleChange('logoUrl', e.target.value)}
              className="w-full px-3 py-2 rounded-xl border border-slate-200 text-sm"
              placeholder="https://.../logo.png"
            />
          </div>
        </div>

        <div className="pt-4">
          <button
            type="button"
            onClick={handleSave}
            disabled={isSaving || !form.name}
            className="px-5 py-2 rounded-xl text-xs font-black uppercase tracking-wider bg-primary-600 text-white hover:bg-primary-700 disabled:opacity-60 disabled:cursor-not-allowed flex items-center gap-2"
          >
            {isSaving && <Loader2 className="w-4 h-4 animate-spin" />}
            {isSaving ? 'Сохранение...' : 'Сохранить реквизиты'}
          </button>
        </div>
      </div>
    </div>
  );
};
