import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { authApi, familyApi } from '../api/client';
import { useStore } from '../store/useStore';
import {
  Shield,
  Home,
  LogOut,
  Users,
  Plus,
  Trash2,
  Lock,
  ArrowLeft,
} from 'lucide-react';

export default function AdminPanel() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { user, logout: storeLogout } = useStore();

  const [newFamilyName, setNewFamilyName] = useState('');
  const [newFamilyPassword, setNewFamilyPassword] = useState('');
  const [families, setFamilies] = useState<Array<{ id: number; name: string }>>([]);

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

  const handleLogout = async () => {
    try {
      await authApi.logout();
      storeLogout();
      navigate('/');
    } catch (err) {
      console.error('Logout error:', err);
    }
  };

  const loadFamilies = async () => {
    try {
      const response = await familyApi.getAll();
      setFamilies(response.data);
    } catch (err) {
      console.error('Error loading families:', err);
    }
  };

  const handleCreateFamily = async () => {
    if (!newFamilyName.trim() || !newFamilyPassword.trim()) {
      alert(t('admin.fillNameAndPassword'));
      return;
    }

    try {
      await familyApi.create({ name: newFamilyName, password: newFamilyPassword });
      setNewFamilyName('');
      setNewFamilyPassword('');
      loadFamilies();
    } catch (err) {
      alert(t('admin.createError'));
      console.error(err);
    }
  };

  const handleDeleteFamily = async (id: number) => {
    if (!confirm(t('admin.deleteConfirm'))) return;

    try {
      await familyApi.delete(id);
      loadFamilies();
    } catch (err) {
      alert(t('admin.deleteError'));
      console.error(err);
    }
  };

  if (!user?.is_admin) {
    return (
      <div className="min-h-screen gradient-bg flex items-center justify-center py-8 sm:py-12 px-4">
        <div className="max-w-md w-full">
          <div className="glass-effect rounded-2xl shadow-2xl p-6 sm:p-8 text-center">
            <div className="flex items-center justify-center mb-6">
              <div className="p-4 btn-danger text-white rounded-2xl">
                <Shield className="w-10 h-10 sm:w-12 sm:h-12" />
              </div>
            </div>
            <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-2">
              {t('admin.accessDenied')}
            </h1>
            <p className="text-gray-600 mb-6 text-sm sm:text-base">
              {t('admin.requiresAdmin')}
            </p>
            <button
              onClick={() => navigate('/')}
              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gray-200 hover:bg-gray-300 text-gray-700 rounded-xl transition-all duration-300 font-medium"
            >
              <ArrowLeft className="w-5 h-5" />
              {t('common.back')}
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen gradient-bg py-8 sm:py-12 px-4">
      <div className="max-w-4xl mx-auto">
        <div className="text-center mb-8">
          <div className="inline-flex p-4 bg-white/20 backdrop-blur-md rounded-2xl mb-4">
            <Shield className="w-12 h-12 text-white" />
          </div>
          <h1 className="text-4xl sm:text-5xl font-bold text-white mb-2">
            {t('admin.title')}
          </h1>
          <p className="text-purple-100 text-base sm:text-lg mb-6">
            {t('admin.subtitle')}
          </p>
          <div className="flex justify-center gap-3">
            <button
              onClick={handleLogout}
              className="inline-flex items-center gap-2 px-5 py-3 bg-red-500/80 hover:bg-red-600 text-white rounded-2xl backdrop-blur-md transition-all duration-300 hover:shadow-lg font-medium"
            >
              <LogOut className="w-5 h-5" />
              {t('common.exit')}
            </button>
            <button
              onClick={() => navigate('/')}
              className="inline-flex items-center gap-2 px-5 py-3 bg-white/20 hover:bg-white/30 text-white rounded-2xl backdrop-blur-md transition-all duration-300 hover:shadow-lg font-medium"
            >
              <Home className="w-5 h-5" />
              {t('common.toHome')}
            </button>
          </div>
        </div>

        <div className="glass-effect rounded-3xl shadow-xl p-6 sm:p-10 mb-6 max-w-2xl mx-auto">
          <div className="flex items-center justify-center gap-3 mb-8">
            <div className="p-3 btn-success rounded-2xl">
              <Plus className="w-8 h-8 text-white" />
            </div>
            <h2 className="text-2xl sm:text-3xl font-bold text-gray-800">
              {t('admin.createFamily')}
            </h2>
          </div>

          <div className="space-y-5">
            <div>
              <label className="flex items-center justify-center gap-2 text-sm font-semibold text-gray-700 mb-3">
                <Users className="w-5 h-5 text-purple-600" />
                {t('admin.familyName')}
              </label>
              <input
                type="text"
                placeholder={t('admin.familyNamePlaceholder')}
                value={newFamilyName}
                onChange={(e) => setNewFamilyName(e.target.value)}
                className="w-full px-5 py-4 border-2 border-gray-300 rounded-2xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition-all font-medium text-center"
              />
            </div>
            <div>
              <label className="flex items-center justify-center gap-2 text-sm font-semibold text-gray-700 mb-3">
                <Lock className="w-5 h-5 text-purple-600" />
                {t('admin.familyPassword')}
              </label>
              <input
                type="password"
                placeholder={t('admin.familyPasswordPlaceholder')}
                value={newFamilyPassword}
                onChange={(e) => setNewFamilyPassword(e.target.value)}
                className="w-full px-5 py-4 border-2 border-gray-300 rounded-2xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition-all font-medium text-center"
              />
            </div>
            <button
              onClick={handleCreateFamily}
              className="w-full flex items-center justify-center gap-2 px-6 py-4 btn-success text-white rounded-2xl hover:shadow-xl transition-all duration-300 font-semibold text-lg"
            >
              <Plus className="w-6 h-6" />
              {t('admin.createButton')}
            </button>
          </div>
        </div>

        <div className="glass-effect rounded-3xl shadow-xl p-6 sm:p-10 max-w-3xl mx-auto">
          <div className="flex items-center justify-center gap-3 mb-8">
            <div className="p-3 category-icon rounded-2xl">
              <Users className="w-8 h-8 text-white" />
            </div>
            <h2 className="text-2xl sm:text-3xl font-bold text-gray-800">
              {t('admin.familyList')}
            </h2>
          </div>

          {families.length === 0 ? (
            <div className="text-center py-16 sm:py-20">
              <div className="inline-flex p-6 bg-gray-100 rounded-3xl mb-6">
                <Users className="w-20 h-20 text-gray-400" />
              </div>
              <p className="text-gray-600 text-lg sm:text-xl mb-2 font-semibold">
                {t('admin.noFamilies')}
              </p>
              <p className="text-gray-500 text-sm sm:text-base">
                {t('admin.createFirst')}
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {families.map((family) => (
                <div
                  key={family.id}
                  className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 p-5 bg-gray-50 rounded-2xl border-2 border-gray-200 card-hover"
                >
                  <div className="flex items-center gap-3">
                    <div className="p-3 category-icon text-white rounded-xl shadow-md">
                      <Users className="w-6 h-6" />
                    </div>
                    <span className="text-lg sm:text-xl font-bold text-gray-900">
                      {family.name}
                    </span>
                  </div>
                  <button
                    onClick={() => handleDeleteFamily(family.id)}
                    className="w-full sm:w-auto flex items-center justify-center gap-2 px-5 py-3 btn-danger text-white rounded-xl transition-all font-semibold shadow-md hover:shadow-lg"
                  >
                    <Trash2 className="w-5 h-5" />
                    {t('common.delete')}
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
