import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Link, useLocation } from 'react-router-dom';
import { Layout, Button, message, Grid, Skeleton, Dropdown } from 'antd';
import { DownOutlined, KeyOutlined, LogoutOutlined, CreditCardOutlined } from '@ant-design/icons';
import Index from './pages/Index';
import Tank from './pages/Tank';
import EditCustomer from './pages/EditCustomer';
import Order from './pages/Order';
import Login from './pages/auth/Login';
import Register from './pages/auth/Register';
import New from './pages/auth/new';
import ForgotPassword from './pages/auth/ForgotPassword';
import ResetPassword from './pages/auth/ResetPassword';
import ChangePassword from './pages/auth/ChangePassword';
import Payments from './pages/Payments';
import logo from './assets/images/1.png';
import './App.css';
import api from './utils/api';
import { colors, spacing, fontSize, buttonStyles } from './theme';

const { Header, Content, Footer } = Layout;
const { useBreakpoint } = Grid;

function AppContent() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const location = useLocation();
  const screens = useBreakpoint();

  useEffect(() => {
    checkAuthStatus();
  }, [location]); // Re-check auth when location changes

  const checkAuthStatus = async () => {
    const token = localStorage.getItem('token');
    if (token) {
      try {
        // Try to get current user info from backend
        const response = await api.get('/auth/me');
        setUser(response.data);
      } catch (error) {
        // Token invalid, remove it
        localStorage.removeItem('token');
        setUser(null);
      }
    } else {
      setUser(null);
    }
    setLoading(false);
  };

  const handleLogout = () => {
    localStorage.removeItem('token');
    setUser(null);
    message.success('Logged out successfully');
  };

  if (loading) {
    return (
      <Layout className="layout">
        <Header className="bg-blue-oil">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', padding: `0 ${spacing.md}px` }}>
            <Skeleton.Input active style={{ width: 120, height: 32 }} />
            <Skeleton.Input active style={{ width: 80, height: 24 }} />
          </div>
        </Header>
        <Content style={{ padding: `0 ${spacing.content.desktop}px` }}>
          <div className="site-layout-content">
            <Skeleton active paragraph={{ rows: 6 }} />
          </div>
        </Content>
      </Layout>
    );
  }

  return (
    <Layout className="layout">
      <Header className="bg-blue-oil">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', width: '100%', height: '100%', padding: `0 ${spacing.md}px` }}>
          <Link to="/" style={{ display: 'flex', alignItems: 'center' }}><img src={logo} alt="Oil Customer Gateway" className="logo" style={{ height: 32, width: 'auto' }} /></Link>
          <div style={{ display: 'flex', alignItems: 'center', gap: spacing.xs }}>
            {user ? (
              <Dropdown
                menu={{
                  items: [
                    {
                      key: 'payments',
                      icon: <CreditCardOutlined />,
                      label: <Link to="/payments" style={{ color: 'inherit' }}>Payments</Link>,
                    },
                    {
                      key: 'change-password',
                      icon: <KeyOutlined />,
                      label: <Link to="/change-password" style={{ color: 'inherit' }}>Change Password</Link>,
                    },
                    {
                      type: 'divider',
                    },
                    {
                      key: 'logout',
                      icon: <LogoutOutlined />,
                      label: 'Logout',
                      onClick: handleLogout,
                    },
                  ],
                }}
                trigger={['click']}
              >
                <Button type="text" size="small" style={buttonStyles.headerText}>
                  <span style={{ display: screens.sm ? 'inline' : 'none' }}>Welcome, {user.customer_first_name}</span>
                  <span style={{ display: screens.sm ? 'none' : 'inline' }}>{user.customer_first_name}</span>
                  <DownOutlined style={{ marginLeft: 4, fontSize: 10 }} />
                </Button>
              </Dropdown>
            ) : (
              <>
                <Link to="/login"><Button type="text" size="small" style={buttonStyles.headerText}>Login</Button></Link>
                <Link to="/register"><Button type="text" size="small" style={{ ...buttonStyles.headerText, display: screens.sm ? 'inline' : 'none' }}>Register</Button></Link>
                <Link to="/new"><Button type="text" size="small" style={{ ...buttonStyles.headerText, display: screens.sm ? 'inline' : 'none' }}>New</Button></Link>
              </>
            )}
          </div>
        </div>
      </Header>
      <Content style={{ padding: screens.md ? `0 ${spacing.content.desktop}px` : `0 ${spacing.md}px` }}>
        <div className="site-layout-content">
          <Routes>
            <Route path="/" element={<Index />} />
            <Route path="/tank" element={<Tank />} />
            <Route path="/edit-customer" element={<EditCustomer />} />
            <Route path="/order" element={<Order />} />
            <Route path="/login" element={<Login />} />
            <Route path="/forgot-password" element={<ForgotPassword />} />
            <Route path="/reset-password" element={<ResetPassword />} />
            <Route path="/change-password" element={<ChangePassword />} />
            <Route path="/payments" element={<Payments />} />
            <Route path="/new" element={<New />} />
            <Route path="/register" element={<Register />} />
          </Routes>
        </div>
      </Content>
      <Footer style={{ textAlign: 'center' }}>Rocket Services LLC ©{new Date().getFullYear()}</Footer>
    </Layout>
  );
}

function App() {
  return (
    <Router>
      <AppContent />
    </Router>
  );
}

export default App;
