import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth } from '../context/AuthContext';
import { organizations, users } from '../services/api';

export default function Settings() {
    const { currentOrg, selectOrg, user } = useAuth();
    const queryClient = useQueryClient();
    const [activeTab, setActiveTab] = useState('profile');
    const [profileForm, setProfileForm] = useState({ full_name: user?.full_name || '' });
    const [orgForm, setOrgForm] = useState({ name: currentOrg?.name || '', slug: currentOrg?.slug || '' });
    const [newOrgForm, setNewOrgForm] = useState({ name: '', slug: '' });
    
    const updateProfileMutation = useMutation({
        mutationFn: (data) => users.updateMe(data),
        onSuccess: () => queryClient.invalidateQueries(['user'])
    });
    
    const updateOrgMutation = useMutation({
        mutationFn: (data) => organizations.update(currentOrg.id, data),
        onSuccess: (res) => {
            queryClient.invalidateQueries(['organizations']);
            selectOrg(res.data);
        }
    });
    
    const createOrgMutation = useMutation({
        mutationFn: (data) => organizations.create(data),
        onSuccess: (res) => {
            queryClient.invalidateQueries(['organizations']);
            selectOrg(res.data);
            setNewOrgForm({ name: '', slug: '' });
        }
    });
    
    const tabs = [
        { id: 'profile', label: 'Profile', icon: '👤' },
        { id: 'organization', label: 'Organization', icon: '🏢' },
        { id: 'new-org', label: 'New Organization', icon: '➕' }
    ];
    
    return (
        <div className="p-8">
            <h1 className="text-2xl font-bold mb-6">Settings</h1>
            
            <div className="flex gap-8">
                {/* Tabs */}
                <div className="w-48 space-y-1">
                    {tabs.map(tab => (
                        <button
                            key={tab.id}
                            onClick={() => setActiveTab(tab.id)}
                            className={`w-full text-left px-4 py-2 rounded-lg flex items-center gap-2 ${
                                activeTab === tab.id ? 'bg-primary-600 text-white' : 'text-gray-400 hover:bg-gray-700'
                            }`}
                        >
                            <span>{tab.icon}</span>
                            <span>{tab.label}</span>
                        </button>
                    ))}
                </div>
                
                {/* Content */}
                <div className="flex-1">
                    {activeTab === 'profile' && (
                        <div className="card max-w-xl">
                            <h2 className="text-lg font-semibold mb-4">Profile Settings</h2>
                            <div className="space-y-4">
                                <div>
                                    <label className="block text-sm font-medium mb-2">Email</label>
                                    <input type="email" value={user?.email || ''} disabled className="input bg-gray-900" />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium mb-2">Full Name</label>
                                    <input
                                        type="text"
                                        value={profileForm.full_name}
                                        onChange={(e) => setProfileForm({...profileForm, full_name: e.target.value})}
                                        className="input"
                                    />
                                </div>
                                <button 
                                    onClick={() => updateProfileMutation.mutate(profileForm)}
                                    disabled={updateProfileMutation.isPending}
                                    className="btn btn-primary"
                                >
                                    {updateProfileMutation.isPending ? 'Saving...' : 'Save Profile'}
                                </button>
                            </div>
                        </div>
                    )}
                    
                    {activeTab === 'organization' && currentOrg && (
                        <div className="card max-w-xl">
                            <h2 className="text-lg font-semibold mb-4">Organization Settings</h2>
                            <div className="space-y-4">
                                <div>
                                    <label className="block text-sm font-medium mb-2">Organization Name</label>
                                    <input
                                        type="text"
                                        value={orgForm.name}
                                        onChange={(e) => setOrgForm({...orgForm, name: e.target.value})}
                                        className="input"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium mb-2">Slug</label>
                                    <input
                                        type="text"
                                        value={orgForm.slug}
                                        onChange={(e) => setOrgForm({...orgForm, slug: e.target.value})}
                                        className="input"
                                    />
                                </div>
                                
                                <div className="pt-4 border-t border-gray-700">
                                    <h3 className="font-medium mb-2">Webhook Base URL</h3>
                                    <code className="block p-3 bg-gray-900 rounded-lg text-sm text-primary-400 break-all">
                                        https://jira-fixer.startdata.com.br/api/webhook/{currentOrg.id}/
                                    </code>
                                    <p className="text-xs text-gray-400 mt-2">
                                        Append: jira, servicenow, zendesk, github, gitlab, tickethub, or generic
                                    </p>
                                </div>
                                
                                <button 
                                    onClick={() => updateOrgMutation.mutate(orgForm)}
                                    disabled={updateOrgMutation.isPending}
                                    className="btn btn-primary"
                                >
                                    {updateOrgMutation.isPending ? 'Saving...' : 'Save Organization'}
                                </button>
                            </div>
                        </div>
                    )}
                    
                    {activeTab === 'new-org' && (
                        <div className="card max-w-xl">
                            <h2 className="text-lg font-semibold mb-4">Create New Organization</h2>
                            <div className="space-y-4">
                                <div>
                                    <label className="block text-sm font-medium mb-2">Organization Name</label>
                                    <input
                                        type="text"
                                        value={newOrgForm.name}
                                        onChange={(e) => setNewOrgForm({...newOrgForm, name: e.target.value})}
                                        className="input"
                                        placeholder="Acme Corp"
                                    />
                                </div>
                                <div>
                                    <label className="block text-sm font-medium mb-2">Slug (URL-friendly)</label>
                                    <input
                                        type="text"
                                        value={newOrgForm.slug}
                                        onChange={(e) => setNewOrgForm({...newOrgForm, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '')})}
                                        className="input"
                                        placeholder="acme-corp"
                                    />
                                </div>
                                <button 
                                    onClick={() => createOrgMutation.mutate(newOrgForm)}
                                    disabled={!newOrgForm.name || !newOrgForm.slug || createOrgMutation.isPending}
                                    className="btn btn-primary"
                                >
                                    {createOrgMutation.isPending ? 'Creating...' : 'Create Organization'}
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
}
