'use client';

import { useEffect, useState } from 'react';
import { Save, Upload, MapPin, Phone, Clock, Globe } from 'lucide-react';
import { api } from '@/lib/api';

type ClubSettings = {
  name: string;
  legalName: string;
  address: string;
  phone: string;
  email: string;
  website: string;
  workingHours: string;
  timezone: string;
  description: string;
  logoUrl: string | null;
};

const emptySettings: ClubSettings = {
  name: '',
  legalName: '',
  address: '',
  phone: '',
  email: '',
  website: '',
  workingHours: '',
  timezone: '',
  description: '',
  logoUrl: null,
};

export default function SettingsPage(): React.JSX.Element {
  const [settings, setSettings] = useState<ClubSettings>(emptySettings);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);

  useEffect(() => {
    api.get<ClubSettings>('/clubs/settings')
      .then((res) => {
        setSettings(res);
        setError(null);
      })
      .catch((err) => {
        setError(err instanceof Error ? err.message : 'Не удалось загрузить настройки');
      })
      .finally(() => setLoading(false));
  }, []);

  const updateField = (field: keyof ClubSettings, value: string) => {
    setSettings((prev) => ({ ...prev, [field]: value }));
  };

  const handleSave = async () => {
    setSaving(true);
    setSaveError(null);
    try {
      const updated = await api.patch<ClubSettings>('/clubs/settings', settings);
      setSettings(updated);
    } catch (err) {
      setSaveError(err instanceof Error ? err.message : 'Не удалось сохранить настройки');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-error text-sm mb-2">{error}</p>
          <button
            onClick={() => window.location.reload()}
            className="text-sm text-primary hover:underline"
          >
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Настройки клуба</h1>
          <p className="text-sm text-muted mt-1">Общие настройки вашего фитнес-клуба</p>
        </div>
        <div className="flex items-center gap-3">
          {saveError && (
            <p className="text-sm text-error">{saveError}</p>
          )}
          <button
            onClick={() => void handleSave()}
            disabled={saving}
            className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors disabled:opacity-50"
          >
            <Save className="h-4 w-4" />
            {saving ? 'Сохранение...' : 'Сохранить изменения'}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-6">
          <div className="bg-card rounded-xl p-6 shadow-sm border border-border">
            <h2 className="text-base font-semibold text-gray-900 mb-4">
              Основная информация
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Название клуба
                </label>
                <input
                  type="text"
                  value={settings.name}
                  onChange={(e) => updateField('name', e.target.value)}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Юридическое наименование
                </label>
                <input
                  type="text"
                  value={settings.legalName}
                  onChange={(e) => updateField('legalName', e.target.value)}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Описание
                </label>
                <textarea
                  value={settings.description}
                  onChange={(e) => updateField('description', e.target.value)}
                  rows={3}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary resize-none"
                />
              </div>
            </div>
          </div>

          <div className="bg-card rounded-xl p-6 shadow-sm border border-border">
            <h2 className="text-base font-semibold text-gray-900 mb-4">
              Контактная информация
            </h2>
            <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">
                  <MapPin className="h-3.5 w-3.5 inline mr-1" />
                  Адрес
                </label>
                <input
                  type="text"
                  value={settings.address}
                  onChange={(e) => updateField('address', e.target.value)}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  <Phone className="h-3.5 w-3.5 inline mr-1" />
                  Телефон
                </label>
                <input
                  type="text"
                  value={settings.phone}
                  onChange={(e) => updateField('phone', e.target.value)}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Email
                </label>
                <input
                  type="email"
                  value={settings.email}
                  onChange={(e) => updateField('email', e.target.value)}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  <Globe className="h-3.5 w-3.5 inline mr-1" />
                  Веб-сайт
                </label>
                <input
                  type="url"
                  value={settings.website}
                  onChange={(e) => updateField('website', e.target.value)}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                />
              </div>
            </div>
          </div>

          <div className="bg-card rounded-xl p-6 shadow-sm border border-border">
            <h2 className="text-base font-semibold text-gray-900 mb-4">
              Режим работы
            </h2>
            <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">
                  <Clock className="h-3.5 w-3.5 inline mr-1" />
                  Часы работы
                </label>
                <input
                  type="text"
                  value={settings.workingHours}
                  onChange={(e) => updateField('workingHours', e.target.value)}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Часовой пояс
                </label>
                <input
                  type="text"
                  value={settings.timezone}
                  onChange={(e) => updateField('timezone', e.target.value)}
                  className="w-full px-3 py-2 border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                  readOnly
                />
              </div>
            </div>
          </div>
        </div>

        <div>
          <div className="bg-card rounded-xl p-6 shadow-sm border border-border">
            <h2 className="text-base font-semibold text-gray-900 mb-4">
              Логотип клуба
            </h2>
            <div className="border-2 border-dashed border-border rounded-xl p-8 text-center">
              <Upload className="h-10 w-10 text-muted mx-auto mb-3" />
              <p className="text-sm text-gray-600 mb-1">
                Перетащите файл или нажмите для загрузки
              </p>
              <p className="text-xs text-muted">
                PNG, JPG до 2 МБ, рекомендуется 512x512
              </p>
              <button className="mt-4 px-4 py-2 rounded-lg border border-border text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors">
                Выбрать файл
              </button>
            </div>
          </div>

        </div>
      </div>
    </div>
  );
}
