import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { 
  Settings as SettingsIcon, 
  User, 
  Key, 
  Bell, 
  Shield,
  Save,
  Eye,
  EyeOff
} from 'lucide-react'
import { billingAPI, usersAPI } from '../services/api'
import toast from 'react-hot-toast'

const Settings = () => {
  const [activeTab, setActiveTab] = useState('profile')
  const [showApiKey, setShowApiKey] = useState(false)
  const [profileData, setProfileData] = useState({
    first_name: '',
    last_name: '',
    email: '',
    company_name: '',
    phone_number: '',
  })
  const [passwordData, setPasswordData] = useState({
    old_password: '',
    new_password: '',
    confirm_password: '',
  })

  const { data: user } = useQuery({
    queryKey: ['user'],
    queryFn: usersAPI.getUser,
  })

  const { data: usageStats } = useQuery({
    queryKey: ['usageStats'],
    queryFn: billingAPI.getUsageStats,
  })

  const { data: subscriptionInfo } = useQuery({
    queryKey: ['subscriptionInfo'],
    queryFn: billingAPI.getSubscriptionInfo,
  })

  const handleUpdateProfile = async (e) => {
    e.preventDefault()
    try {
      await usersAPI.updateUser(user.id, profileData)
      toast.success('Profile updated successfully')
    } catch (error) {
      toast.error('Failed to update profile')
    }
  }

  const handleChangePassword = async (e) => {
    e.preventDefault()
    if (passwordData.new_password !== passwordData.confirm_password) {
      toast.error('Passwords do not match')
      return
    }
    try {
      await usersAPI.changePassword(passwordData)
      toast.success('Password changed successfully')
      setPasswordData({ old_password: '', new_password: '', confirm_password: '' })
    } catch (error) {
      toast.error('Failed to change password')
    }
  }

  const handleRegenerateApiKey = async () => {
    try {
      await usersAPI.regenerateApiKey()
      toast.success('API key regenerated successfully')
    } catch (error) {
      toast.error('Failed to regenerate API key')
    }
  }

  const tabs = [
    { id: 'profile', name: 'Profile', icon: User },
    { id: 'security', name: 'Security', icon: Shield },
    { id: 'api', name: 'API Keys', icon: Key },
    { id: 'billing', name: 'Billing', icon: SettingsIcon },
    { id: 'notifications', name: 'Notifications', icon: Bell },
  ]

  return (
    <div className="space-y-6">
      {/* Header */}
      <div>
        <h1 className="text-xl font-bold text-gray-900 dark:text-white">
          Settings
        </h1>
        <p className="text-sm text-gray-600 dark:text-gray-400">
          Manage your account settings and preferences
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* Sidebar */}
        <div className="lg:col-span-1">
          <nav className="space-y-1">
            {tabs.map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`w-full flex items-center px-3 py-2 text-sm font-medium rounded-md ${
                  activeTab === tab.id
                    ? 'bg-primary-100 text-primary-700 dark:bg-primary-900/20 dark:text-primary-400'
                    : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50 dark:text-gray-400 dark:hover:text-gray-300 dark:hover:bg-gray-700'
                }`}
              >
                <tab.icon className="h-4 w-4 mr-3" />
                {tab.name}
              </button>
            ))}
          </nav>
        </div>

        {/* Content */}
        <div className="lg:col-span-3">
          {activeTab === 'profile' && (
            <div className="card p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-6">
                Profile Information
              </h3>
              <form onSubmit={handleUpdateProfile} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="label">First Name</label>
                    <input
                      type="text"
                      value={profileData.first_name}
                      onChange={(e) => setProfileData({...profileData, first_name: e.target.value})}
                      className="input"
                    />
                  </div>
                  <div>
                    <label className="label">Last Name</label>
                    <input
                      type="text"
                      value={profileData.last_name}
                      onChange={(e) => setProfileData({...profileData, last_name: e.target.value})}
                      className="input"
                    />
                  </div>
                </div>
                <div>
                  <label className="label">Email</label>
                  <input
                    type="email"
                    value={profileData.email}
                    onChange={(e) => setProfileData({...profileData, email: e.target.value})}
                    className="input"
                  />
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="label">Company Name</label>
                    <input
                      type="text"
                      value={profileData.company_name}
                      onChange={(e) => setProfileData({...profileData, company_name: e.target.value})}
                      className="input"
                    />
                  </div>
                  <div>
                    <label className="label">Phone Number</label>
                    <input
                      type="tel"
                      value={profileData.phone_number}
                      onChange={(e) => setProfileData({...profileData, phone_number: e.target.value})}
                      className="input"
                    />
                  </div>
                </div>
                <button type="submit" className="btn btn-primary">
                  <Save className="h-4 w-4 mr-2" />
                  Save Changes
                </button>
              </form>
            </div>
          )}

          {activeTab === 'security' && (
            <div className="card p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-6">
                Security Settings
              </h3>
              <form onSubmit={handleChangePassword} className="space-y-6">
                <div>
                  <label className="label">Current Password</label>
                  <input
                    type="password"
                    value={passwordData.old_password}
                    onChange={(e) => setPasswordData({...passwordData, old_password: e.target.value})}
                    className="input"
                  />
                </div>
                <div>
                  <label className="label">New Password</label>
                  <input
                    type="password"
                    value={passwordData.new_password}
                    onChange={(e) => setPasswordData({...passwordData, new_password: e.target.value})}
                    className="input"
                  />
                </div>
                <div>
                  <label className="label">Confirm New Password</label>
                  <input
                    type="password"
                    value={passwordData.confirm_password}
                    onChange={(e) => setPasswordData({...passwordData, confirm_password: e.target.value})}
                    className="input"
                  />
                </div>
                <button type="submit" className="btn btn-primary">
                  <Save className="h-4 w-4 mr-2" />
                  Change Password
                </button>
              </form>
            </div>
          )}

          {activeTab === 'api' && (
            <div className="card p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-6">
                API Keys
              </h3>
              <div className="space-y-6">
                <div className="p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
                  <div className="flex items-center justify-between">
                    <div>
                      <h4 className="font-medium text-gray-900 dark:text-white">Main API Key</h4>
                      <p className="text-sm text-gray-500 dark:text-gray-400">
                        Use this key to authenticate API requests
                      </p>
                    </div>
                    <button
                      onClick={() => setShowApiKey(!showApiKey)}
                      className="btn btn-secondary btn-sm"
                    >
                      {showApiKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                    </button>
                  </div>
                  <div className="mt-3">
                    <div className="flex items-center space-x-2">
                      <input
                        type={showApiKey ? 'text' : 'password'}
                        value={user?.api_key || 'Not available'}
                        readOnly
                        className="input flex-1 font-mono text-sm"
                      />
                      <button
                        onClick={handleRegenerateApiKey}
                        className="btn btn-primary btn-sm"
                      >
                        Regenerate
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'billing' && (
            <div className="space-y-6">
              <div className="card p-6">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-6">
                  Subscription Information
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <h4 className="font-medium text-gray-900 dark:text-white mb-2">Current Plan</h4>
                    <p className="text-xl font-bold text-primary-600">
                      {subscriptionInfo?.subscription_type || 'Free'}
                    </p>
                  </div>
                  <div>
                    <h4 className="font-medium text-gray-900 dark:text-white mb-2">API Access</h4>
                    <p className={`text-lg font-medium ${
                      subscriptionInfo?.is_api_enabled ? 'text-green-600' : 'text-red-600'
                    }`}>
                      {subscriptionInfo?.is_api_enabled ? 'Enabled' : 'Disabled'}
                    </p>
                  </div>
                </div>
              </div>

              <div className="card p-6">
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-6">
                  Usage Statistics
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  <div className="text-center">
                    <p className="text-xl font-bold text-gray-900 dark:text-white">
                      {usageStats?.current_usage?.api_calls_this_month || 0}
                    </p>
                    <p className="text-sm text-gray-500 dark:text-gray-400">API Calls This Month</p>
                    <p className="text-xs text-gray-400">
                      Limit: {usageStats?.limits?.api_calls_per_month || 0}
                    </p>
                  </div>
                  <div className="text-center">
                    <p className="text-xl font-bold text-gray-900 dark:text-white">
                      {usageStats?.current_usage?.reports_this_month || 0}
                    </p>
                    <p className="text-sm text-gray-500 dark:text-gray-400">Reports This Month</p>
                    <p className="text-xs text-gray-400">
                      Limit: {usageStats?.limits?.reports_per_month || 0}
                    </p>
                  </div>
                  <div className="text-center">
                    <p className="text-xl font-bold text-gray-900 dark:text-white">
                      {usageStats?.current_usage?.forecast_requests_this_month || 0}
                    </p>
                    <p className="text-sm text-gray-500 dark:text-gray-400">Forecasts This Month</p>
                    <p className="text-xs text-gray-400">
                      Limit: {usageStats?.limits?.forecast_requests_per_month || 0}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'notifications' && (
            <div className="card p-6">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-6">
                Notification Preferences
              </h3>
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium text-gray-900 dark:text-white">Email Notifications</h4>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      Receive updates via email
                    </p>
                  </div>
                  <input type="checkbox" className="rounded border-gray-300" defaultChecked />
                </div>
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium text-gray-900 dark:text-white">Report Ready</h4>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      Get notified when reports are ready
                    </p>
                  </div>
                  <input type="checkbox" className="rounded border-gray-300" defaultChecked />
                </div>
                <div className="flex items-center justify-between">
                  <div>
                    <h4 className="font-medium text-gray-900 dark:text-white">Usage Alerts</h4>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      Get notified when approaching limits
                    </p>
                  </div>
                  <input type="checkbox" className="rounded border-gray-300" defaultChecked />
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default Settings

