import React, { useState, useMemo, useEffect, useCallback } from 'react';
import { Search, Plus, Trash2, Edit2, Loader2, User, Key, Save, Building2, Users } from 'lucide-react';
const SmartTable = React.lazy(() => import('@/features/dev-tools/components/SmartTable')); // Universal Connector
import { GrFormSidebar } from '../components/GrFormSidebar';
import { GrUserForm } from '../components/GrUserForm'; // Import New Component
import { handleGrError } from '../utils/grErrorHandler'; // Import Error Handler
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { toast } from 'sonner';
import { useGrStore } from '../services/useGrStore';
import * as grService from '../services/grService';

const SettingsView = () => {
  const { userData } = useGrStore();
  const userGroup = userData?.usuario?.grupo || 'Despachante';
  const isAdmin = userGroup === 'Administrador';

  const [activeTab, setActiveTab] = useState('usuarios');
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isBaseSidebarOpen, setIsBaseSidebarOpen] = useState(false);
  const [isResponsibleSidebarOpen, setIsResponsibleSidebarOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(false);
  
  // Data States
  const [users, setUsers] = useState([]);
  const [bases, setBases] = useState([]);
  const [responsibles, setResponsibles] = useState([]);
  const [groups, setGroups] = useState([]);
  
  // Password change state
  const [passwordData, setPasswordData] = useState({
    password: '',
    confirmPassword: ''
  });

  const [formData, setFormData] = useState({
    idusuarios_pralog: null,
    nome_completo: '',
    email: '',
    password: '',
    setor: 'Gestão de Risco', // Default as requested
    base: [], // Changed to array for multi-select
    responsavel_base: '',
    grupo: '',
    modalidade: ''
  });

  const [baseFormData, setBaseFormData] = useState({
    idbase: null,
    base: ''
  });

  const [responsibleFormData, setResponsibleFormData] = useState({
    id_responsavel_base: null,
    responsavel_base: ''
  });

  const fetchData = useCallback(async () => {
    if (!isAdmin) return;
    setLoading(true);
    try {
      const [usersResponse, basesResponse, responsiblesResponse, groupsResponse] = await Promise.all([
        grService.getUserList(),
        grService.getBases(),
        grService.getBaseResponsibles(),
        grService.getGrGroups()
      ]);
      
      const userList = usersResponse.Base_Dados_API || usersResponse.dados || usersResponse || [];
      const basesList = basesResponse.Base_Dados_API || basesResponse.dados || basesResponse || []; 
      const responsiblesList = responsiblesResponse.Base_Dados_API || responsiblesResponse.dados || responsiblesResponse || [];
      const groupsList = groupsResponse.Base_Dados_API || groupsResponse.dados || groupsResponse || [];
      
      setUsers(Array.isArray(userList) ? userList : []);
      setBases(Array.isArray(basesList) ? basesList : []);
      setResponsibles(Array.isArray(responsiblesList) ? responsiblesList : []);
      setGroups(Array.isArray(groupsList) ? groupsList : []);
    } catch (error) {
      console.error("Error fetching data:", error);
      handleGrError(error, "Erro ao carregar dados.");
    } finally {
      setLoading(false);
    }
  }, [isAdmin]);

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

  // --- Handlers for Users ---
  const handleInputChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  const handleEditUser = (user) => {
    // Determine the correctID key
    const id = user.idusuarios_pralog || user.idUsuariosPralog || user.id;
    
    // Normalize base field - it might come as a string or array
    let selectedBases = [];
    if (user.base) {
      if (Array.isArray(user.base)) {
        selectedBases = user.base;
      } else {
        // Handle CSV string if necessary, but backend usually sends array or single string
        selectedBases = user.base.split(',').map(b => b.trim());
      }
    }

    setFormData({
      idusuarios_pralog: id,
      nome_completo: user.nome || user.nome_completo || '',
      email: user.email || '',
      password: '', // Don't populate password
      setor: 'Gestão de Risco',
      base: selectedBases,
      responsavel_base: user.responsavel_base || user.responsavel || '',
      grupo: user.grupo || user.group || '',
      modalidade: user.modalidade || ''
    });
    setIsSidebarOpen(true);
  };

  const handleAddNewUser = () => {
    setFormData({
      idusuarios_pralog: null,
      nome_completo: '',
      email: '',
      password: '',
      setor: 'Gestão de Risco',
      base: [],
      responsavel_base: '',
      grupo: '',
      modalidade: ''
    });
    setIsSidebarOpen(true);
  };

  const handleSaveUser = async (e) => {
    e.preventDefault();
    try {
      const now = new Date();
      // Ensure setor is always 'Gestão de Risco'
      const payload = {
          ...formData,
          setor: 'Gestão de Risco',
          data_envio: `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} `
      };

      if (formData.idusuarios_pralog) {
        await grService.updateUser(payload);
        toast.success("Usuário atualizado!");
      } else {
        await grService.createUser(payload);
        toast.success("Usuário criado!");
      }
      setIsSidebarOpen(false);
      await fetchData();
    } catch (error) {
      handleGrError(error, "Erro ao salvar usuário.");
    }
  };

  const handlePasswordChange = async (e) => {
    e.preventDefault();
    if (passwordData.password !== passwordData.confirmPassword) {
      toast.error("As senhas não conferem.");
      return;
    }

    if (passwordData.password.length < 4) {
      toast.error("A senha deve ter pelo menos 4 caracteres.");
      return;
    }

    setLoading(true);
    try {
      await grService.changeUserPassword({
        idusuarios_pralog: userData?.usuario?.idusuarios_pralog || userData?.usuario?.id,
        nome_completo: userData?.usuario?.nome_completo,
        password: passwordData.password
      });
      toast.success("Senha alterada com sucesso!");
      setPasswordData({ password: '', confirmPassword: '' });
    } catch (error) {
      handleGrError(error, "Erro ao alterar senha.");
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteUser = async (user) => {
    if (!window.confirm(`Deseja realmente excluir o usuário ${user.nome}?`)) return;
    try {
      await grService.deleteUser(user.idusuarios_pralog || user.id);
      toast.success("Usuário removido.");
      await fetchData();
    } catch (error) {
      handleGrError(error, "Erro ao excluir usuário.");
    }
  };

  // --- Handlers for Bases ---
  const handleAddNewBase = () => {
    setBaseFormData({ idbase: null, base: '' });
    setIsBaseSidebarOpen(true);
  };

  const handleEditBase = (baseItem) => {
    setBaseFormData({
      idbase: baseItem.idbase || baseItem.id || baseItem.id_base,
      base: baseItem.base || baseItem.nome || ''
    });
    setIsBaseSidebarOpen(true);
  };

  const handleDeleteBase = async (baseItem) => {
    const id = baseItem.idbase || baseItem.id_base || baseItem.id;
    if (!window.confirm(`Deseja realmente excluir a base ${baseItem.base}?`)) return;
    try {
      await grService.deleteBase(id);
      toast.success("Base removida.");
      await fetchData();
    } catch (error) {
      handleGrError(error, "Erro ao excluir base.");
    }
  };

  const handleSaveBase = async (e) => {
    e.preventDefault();
    try {
      const payload = { ...baseFormData };
      
      if (baseFormData.idbase) {
        await grService.updateBase(payload);
        toast.success("Base atualizada!");
      } else {
        await grService.saveBase(payload);
        toast.success("Base criada!");
      }
      setIsBaseSidebarOpen(false);
      await fetchData();
    } catch (error) {
       handleGrError(error, "Erro ao salvar base.");
    }
  };

  // --- Handlers for Responsibles ---
  const handleAddNewResponsible = () => {
    setResponsibleFormData({ id_responsavel_base: null, responsavel_base: '' });
    setIsResponsibleSidebarOpen(true);
  };

  const handleEditResponsible = (item) => {
    setResponsibleFormData({
      id_responsavel_base: item.id_responsavel_base || item.idresponsavel_base || item.id || item.id_responsavel,
      responsavel_base: item.responsavel || item.responsavel_base || item.nome || ''
    });
    setIsResponsibleSidebarOpen(true);
  };

  const handleDeleteResponsible = async (item) => {
    const id = item.idresponsavel_base || item.id || item.id_responsavel;
    if (!window.confirm(`Deseja realmente excluir o responsável ${item.responsavel_base || item.responsavel}?`)) return;
    try {
      await grService.deleteBaseResponsible(id);
      toast.success("Responsável removido.");
      await fetchData();
    } catch (error) {
      handleGrError(error, "Erro ao excluir responsável.");
    }
  };

  const handleSaveResponsible = async (e) => {
    e.preventDefault();
    try {
      const payload = { ...responsibleFormData };
      if (responsibleFormData.id_responsavel_base) {
        await grService.updateBaseResponsible(payload);
        toast.success("Responsável atualizado!");
      } else {
        await grService.saveBaseResponsible(payload);
        toast.success("Responsável criado!");
      }
      setIsResponsibleSidebarOpen(false);
      await fetchData();
    } catch (error) {
      handleGrError(error, "Erro ao salvar responsável.");
    }
  };


  // Filtered Lists
  const filteredUsers = useMemo(() => {
    return users.filter(item => 
      (item.nome_completo || item.nome || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
      (item.email || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
      (item.base || '').toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [users, searchTerm]);

  const filteredBases = useMemo(() => {
    return bases.filter(item => 
      (item.base || item.nome || '').toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [bases, searchTerm]);

  const filteredResponsibles = useMemo(() => {
    return responsibles.filter(item => 
      (item.responsavel_base || item.responsavel || item.nome || '').toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [responsibles, searchTerm]);

  // Columns Definitions
  const userColumns = useMemo(() => [
    { field: 'nome', header: 'Nome', width: 200 },
    { field: 'base', header: 'Base', width: 150, render: (row) => (
      <span className="truncate block" title={Array.isArray(row.base) ? row.base.join(', ') : row.base}>
        {Array.isArray(row.base) ? row.base.join(', ') : row.base}
      </span>
    )},
    { field: 'grupo', header: 'Grupo', width: 140 },
    { field: 'setor', header: 'Setor', width: 140 },
    { field: 'responsavel_base', header: 'Responsável', width: 180 },
    { field: 'email', header: 'Email', width: 220 },
    { field: 'acoes', header: 'Ações', width: 100, render: (row) => (
      <div className="flex items-center gap-2 justify-center">
        <button 
          onClick={() => handleEditUser(row)}
          className="p-1.5 hover:bg-slate-100 dark:hover:bg-white/10 rounded-lg transition-colors text-slate-400 hover:text-[var(--gr-primary)]"
        >
            <Edit2 size={14} />
        </button>
        <button 
          onClick={(e) => { e.stopPropagation(); handleDeleteUser(row); }}
          className="p-1.5 hover:bg-slate-100 dark:hover:bg-white/10 rounded-lg transition-colors text-slate-400 hover:text-red-500"
        >
            <Trash2 size={14} />
        </button>
      </div>
    )}
  ], []);

  const baseColumns = useMemo(() => [
    { field: 'id', header: 'ID', width: 80 },
    { field: 'base', header: 'Base', width: 300 },
    { field: 'acoes', header: 'Ações', width: 100, render: (row) => (
      <div className="flex items-center gap-2 justify-center">
        <button 
          onClick={() => handleEditBase(row)}
          className="p-1.5 hover:bg-slate-100 dark:hover:bg-white/10 rounded-lg transition-colors text-slate-400 hover:text-[var(--gr-primary)]"
        >
            <Edit2 size={14} />
        </button>
        <button 
          onClick={(e) => { e.stopPropagation(); handleDeleteBase(row); }}
          className="p-1.5 hover:bg-slate-100 dark:hover:bg-white/10 rounded-lg transition-colors text-slate-400 hover:text-red-500"
        >
            <Trash2 size={14} />
        </button>
      </div>
    )}

  ], []);

  const responsibleColumns = useMemo(() => [
    { field: 'idresponsavel_base', header: 'ID', width: 80 },
    { field: 'responsavel', header: 'Responsável', width: 300 },
    { field: 'acoes', header: 'Ações', width: 100, render: (row) => (
      <div className="flex items-center gap-2 justify-center">
        <button 
          onClick={() => handleEditResponsible(row)}
          className="p-1.5 hover:bg-slate-100 dark:hover:bg-white/10 rounded-lg transition-colors text-slate-400 hover:text-[var(--gr-primary)]"
        >
            <Edit2 size={14} />
        </button>
        <button 
          onClick={(e) => { e.stopPropagation(); handleDeleteResponsible(row); }}
          className="p-1.5 hover:bg-slate-100 dark:hover:bg-white/10 rounded-lg transition-colors text-slate-400 hover:text-red-500"
        >
            <Trash2 size={14} />
        </button>
      </div>
    )}
  ], []);

  if (!isAdmin) {
    return (
      <div className="flex flex-col h-full gap-8 max-w-4xl mx-auto py-8">
        <div className="space-y-2 text-center md:text-left">
          <h1 className="text-4xl md:text-5xl font-bold text-slate-800 dark:text-white tracking-tighter">
            Minhas <span className="text-[var(--gr-primary)]">Configurações</span>
          </h1>
          <p className="text-slate-400 font-medium italic">Gerencie seu perfil e segurança</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
          {/* User Profile Card */}
          <div className="bg-white dark:bg-black/40 p-8 rounded-[32px] border border-slate-100 dark:border-white/5 shadow-sm space-y-6">
            <div className="flex items-center gap-4 border-b border-slate-100 dark:border-white/5 pb-6">
              <div className="w-14 h-14 bg-slate-100 dark:bg-white/5 rounded-2xl flex items-center justify-center text-[var(--gr-primary)]">
                <User size={28} />
              </div>
              <div>
                <h3 className="text-lg font-bold text-slate-800 dark:text-white">{userData?.usuario?.nome_completo}</h3>
                <p className="text-xs font-bold text-slate-400 uppercase tracking-widest">{userData?.usuario?.grupo}</p>
              </div>
            </div>

            <div className="space-y-4">
              <div className="flex flex-col gap-1">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Email</Label>
                <p className="text-sm font-semibold text-slate-700 dark:text-slate-300">{userData?.usuario?.email || 'N/A'}</p>
              </div>
              <div className="flex flex-col gap-1">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Setor</Label>
                <p className="text-sm font-semibold text-slate-700 dark:text-slate-300">{userData?.usuario?.setor || 'N/A'}</p>
              </div>
              <div className="flex flex-col gap-1">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400">Base</Label>
                <p className="text-sm font-semibold text-slate-700 dark:text-slate-300">{userData?.usuario?.base || 'N/A'}</p>
              </div>
            </div>
          </div>

          {/* Password Change Card */}
          <div className="bg-white dark:bg-black/40 p-8 rounded-[32px] border border-slate-100 dark:border-white/5 shadow-sm space-y-6">
             <div className="flex items-center gap-4 border-b border-slate-100 dark:border-white/5 pb-6">
              <div className="w-14 h-14 bg-slate-100 dark:bg-white/5 rounded-2xl flex items-center justify-center text-orange-500">
                <Key size={28} />
              </div>
              <div>
                <h3 className="text-lg font-bold text-slate-800 dark:text-white">Segurança</h3>
                <p className="text-xs font-bold text-slate-400 uppercase tracking-widest">Alterar Senha de Acesso</p>
              </div>
            </div>

            <form onSubmit={handlePasswordChange} className="space-y-6">
              <div className="space-y-2">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Nova Senha</Label>
                <Input 
                  type="password"
                  value={passwordData.password}
                  onChange={(e) => setPasswordData(prev => ({ ...prev, password: e.target.value }))}
                  placeholder="Mínimo 4 caracteres"
                  className="h-12 rounded-2xl bg-slate-50 dark:bg-white/5 border-transparent focus:border-[var(--gr-primary)] transition-all font-semibold"
                  required
                />
              </div>

              <div className="space-y-2">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Confirmar Senha</Label>
                <Input 
                  type="password"
                  value={passwordData.confirmPassword}
                  onChange={(e) => setPasswordData(prev => ({ ...prev, confirmPassword: e.target.value }))}
                  placeholder="Repita a nova senha"
                  className="h-12 rounded-2xl bg-slate-50 dark:bg-white/5 border-transparent focus:border-[var(--gr-primary)] transition-all font-semibold"
                  required
                />
              </div>

              <button 
                type="submit"
                disabled={loading}
                className="w-full py-4 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] disabled:opacity-50 text-white rounded-2xl font-bold uppercase text-[10px] tracking-widest transition-all shadow-lg shadow-[var(--gr-primary)]/20 active:scale-95 flex items-center justify-center gap-2"
              >
                {loading ? <Loader2 className="animate-spin" size={16} /> : <Save size={16} />}
                Alterar Senha
              </button>
            </form>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full gap-4 md:gap-8">
      {/* Header Section */}
      <div className="flex flex-col gap-6">
        <div className="flex flex-col xl:flex-row xl:items-end justify-between gap-8">
            <div className="space-y-1">
                <h1 className="text-3xl md:text-5xl font-bold text-slate-800 dark:text-white tracking-tighter leading-none">
                    Configurações
                </h1>
                <p className="text-slate-400 dark:text-slate-500 text-sm md:text-base font-medium italic opacity-80">
                    Gerencie permissões, usuários e bases do sistema GR
                </p>
            </div>

            <div className="flex flex-wrap items-center gap-4">
                {/* Search */}
                <div className="relative group flex-1 min-w-[260px] max-w-[400px]">
                    <Search size={16} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 group-focus-within:text-[var(--gr-primary)] transition-colors" />
                    <input 
                        type="text" 
                        placeholder={activeTab === 'usuarios' ? "Buscar por nome, email..." : activeTab === 'bases' ? "Buscar base..." : "Buscar responsável..."}
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-12 pr-14 py-3.5 w-full bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-white/5 rounded-[24px] text-xs focus:outline-none focus:ring-4 focus:ring-[var(--gr-primary)]/10 focus:border-[var(--gr-primary)] transition-all font-semibold shadow-sm"
                    />
                </div>

                {/* Add Button */}
                <button 
                  onClick={activeTab === 'usuarios' ? handleAddNewUser : activeTab === 'bases' ? handleAddNewBase : handleAddNewResponsible}
                  className="flex items-center gap-2 px-8 py-3.5 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-[24px] font-bold text-[11px] uppercase tracking-widest transition-all shadow-xl shadow-[var(--gr-primary)]/25 hover:scale-[1.02] active:scale-95"
                >
                    <Plus size={18} strokeWidth={3} />
                    {activeTab === 'usuarios' ? 'Adicionar Usuário' : activeTab === 'bases' ? 'Adicionar Base' : 'Adicionar Responsável'}
                </button>
            </div>
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col overflow-hidden">
        <TabsList className="bg-slate-100 dark:bg-white/5 p-1 rounded-2xl w-fit mb-4">
          <TabsTrigger value="usuarios" className="rounded-xl px-6 py-2.5 text-xs font-bold uppercase tracking-wider data-[state=active]:bg-white dark:data-[state=active]:bg-[#1a1a1a] data-[state=active]:text-[var(--gr-primary)] data-[state=active]:shadow-sm transition-all flex items-center gap-2">
            <Users size={14} />
            Usuários
          </TabsTrigger>
          <TabsTrigger value="bases" className="rounded-xl px-6 py-2.5 text-xs font-bold uppercase tracking-wider data-[state=active]:bg-white dark:data-[state=active]:bg-[#1a1a1a] data-[state=active]:text-[var(--gr-primary)] data-[state=active]:shadow-sm transition-all flex items-center gap-2">
            <Building2 size={14} />
            Bases
          </TabsTrigger>
          <TabsTrigger value="responsaveis" className="rounded-xl px-6 py-2.5 text-xs font-bold uppercase tracking-wider data-[state=active]:bg-white dark:data-[state=active]:bg-[#1a1a1a] data-[state=active]:text-[var(--gr-primary)] data-[state=active]:shadow-sm transition-all flex items-center gap-2">
            <User size={14} />
            Responsáveis
          </TabsTrigger>
        </TabsList>

        <div className="flex-1 min-h-0 bg-white dark:bg-black/20 rounded-[32px] border border-slate-100 dark:border-white/5 overflow-hidden shadow-sm relative">
             <React.Suspense fallback={<div className="flex h-full items-center justify-center"><Loader2 className="animate-spin text-[var(--gr-primary)]" /></div>}>
                <TabsContent value="usuarios" className="h-full m-0 p-0 outline-none">
                    <SmartTable 
                      data={filteredUsers} 
                      columns={userColumns} 
                      loading={loading}
                    />
                </TabsContent>
                <TabsContent value="bases" className="h-full m-0 p-0 outline-none">
                    <SmartTable 
                      data={filteredBases} 
                      columns={baseColumns} 
                      loading={loading}
                    />
                </TabsContent>
                <TabsContent value="responsaveis" className="h-full m-0 p-0 outline-none">
                    <SmartTable 
                      data={filteredResponsibles} 
                      columns={responsibleColumns} 
                      loading={loading}
                    />
                </TabsContent>
             </React.Suspense>
        </div>
      </Tabs>
  
        {/* User Form Sidebar */}
        <GrFormSidebar 
          isOpen={isSidebarOpen} 
          onClose={() => setIsSidebarOpen(false)}
          title={formData.idusuarios_pralog ? "Editar Usuário" : "Novo Usuário"}
          footer={
            <button 
              type="submit"
              form="user-form"
              className="w-full py-4 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-2xl font-bold uppercase text-xs tracking-widest transition-all shadow-lg shadow-[var(--gr-primary)]/20 active:scale-95"
            >
              {formData.idusuarios_pralog ? "Atualizar Usuário" : "Cadastrar Usuário"}
            </button>
          }
      >
        <GrUserForm 
          formData={formData}
          handleInputChange={handleInputChange}
          handleSaveUser={handleSaveUser}
          groups={groups}
          bases={bases}
          responsibles={responsibles}
          isEditing={!!formData.idusuarios_pralog}
        />
      </GrFormSidebar>

      {/* Base Form Sidebar */}
      <GrFormSidebar 
          isOpen={isBaseSidebarOpen} 
          onClose={() => setIsBaseSidebarOpen(false)}
          title={baseFormData.id ? "Editar Base" : "Nova Base"}
          footer={
            <button 
              type="submit"
              form="base-form"
              className="w-full py-4 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-2xl font-bold uppercase text-xs tracking-widest transition-all shadow-lg shadow-[var(--gr-primary)]/20 active:scale-95"
            >
              {baseFormData.idbase ? "Atualizar Base" : "Cadastrar Base"}
            </button>
          }
      >
        <form id="base-form" onSubmit={handleSaveBase} className="space-y-8">
            <div className="space-y-2">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Nome da Base</Label>
                <Input 
                    value={baseFormData.base}
                    onChange={(e) => setBaseFormData(prev => ({ ...prev, base: e.target.value }))}
                    placeholder="Ex: São Cristovão" 
                    className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm" 
                    required
                />
            </div>
        </form>
      </GrFormSidebar>

      {/* Responsible Form Sidebar */}
      <GrFormSidebar 
          isOpen={isResponsibleSidebarOpen} 
          onClose={() => setIsResponsibleSidebarOpen(false)}
          title={responsibleFormData.id ? "Editar Responsável" : "Novo Responsável"}
          footer={
            <button 
              type="submit"
              form="responsible-form"
              className="w-full py-4 bg-[var(--gr-primary)] hover:bg-[var(--gr-primary-dark)] text-white rounded-2xl font-bold uppercase text-xs tracking-widest transition-all shadow-lg shadow-[var(--gr-primary)]/20 active:scale-95"
            >
              {responsibleFormData.id_responsavel_base ? "Atualizar Responsável" : "Cadastrar Responsável"}
            </button>
          }
      >
        <form id="responsible-form" onSubmit={handleSaveResponsible} className="space-y-8">
            <div className="space-y-2">
                <Label className="text-[10px] font-bold uppercase tracking-widest text-slate-400 ml-1">Nome do Responsável</Label>
                <Input 
                    value={responsibleFormData.responsavel_base}
                    onChange={(e) => setResponsibleFormData(prev => ({ ...prev, responsavel_base: e.target.value }))}
                    placeholder="Ex: João Silva" 
                    className="h-12 rounded-2xl bg-white dark:bg-white/5 border-slate-200 dark:border-white/10 shadow-sm" 
                    required
                />
            </div>
        </form>
      </GrFormSidebar>

    </div>
  );
};

export default SettingsView;
