import React, { useState } from 'react';
import { Box, Paper, TextField, Button, Typography, Stack, InputAdornment } from '@mui/material';
import { Storage, Person, Lock, Dns } from '@mui/icons-material';
import { useAppStore } from '../store/useAppStore';
import { SchemaService } from '../services/api';

const Login: React.FC = () => {
  const setConnection = useAppStore((state) => state.setConnection);
  const [config, setConfig] = useState({
    host: '127.0.0.1',
    username: 'root',
    password: '',
    port: 3306,
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleConnect = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
      // Temporarily set connection to test connectivity
      // In a real app, we'd have a specific /connect endpoint
      // Here we just try to fetch databases to verify
      const tempConnection = { ...config };
      setConnection(tempConnection); 
      
      await SchemaService.getDatabases();
      // If success, we are already "connected" in the store
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to connect to database');
      useAppStore.getState().clearConnection();
    } finally {
      setLoading(false);
    }
  };

  return (
    <Box sx={{ 
      height: '100vh', 
      display: 'flex', 
      alignItems: 'center', 
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #0f172a 0%, #1e293b 100%)'
    }}>
      <Paper elevation={24} sx={{ 
        p: 4, 
        width: '100%', 
        maxWidth: 400, 
        borderRadius: 4,
        background: 'rgba(255, 255, 255, 0.05)',
        backdropFilter: 'blur(20px)',
        border: '1px solid rgba(255, 255, 255, 0.1)',
        color: 'white'
      }}>
        <Box sx={{ textAlign: 'center', mb: 4 }}>
          <Typography variant="h4" sx={{ fontWeight: 800, color: '#0061ff', mb: 1 }}>
            MARIAVEL
          </Typography>
          <Typography variant="body2" sx={{ color: 'rgba(255,255,255,0.6)' }}>
            Connect to your MySQL Database
          </Typography>
        </Box>

        <form onSubmit={handleConnect}>
          <Stack spacing={3}>
            <TextField
              label="Host"
              variant="outlined"
              fullWidth
              value={config.host}
              onChange={(e) => setConfig({ ...config, host: e.target.value })}
              InputProps={{
                startAdornment: <InputAdornment position="start"><Dns sx={{ color: 'primary.main' }} /></InputAdornment>,
              }}
              sx={{ '& .MuiOutlinedInput-root': { color: 'white' } }}
            />
            <TextField
              label="Port"
              variant="outlined"
              fullWidth
              type="number"
              value={config.port}
              onChange={(e) => setConfig({ ...config, port: parseInt(e.target.value) })}
              sx={{ '& .MuiOutlinedInput-root': { color: 'white' } }}
            />
            <TextField
              label="Username"
              variant="outlined"
              fullWidth
              value={config.username}
              onChange={(e) => setConfig({ ...config, username: e.target.value })}
              InputProps={{
                startAdornment: <InputAdornment position="start"><Person sx={{ color: 'primary.main' }} /></InputAdornment>,
              }}
              sx={{ '& .MuiOutlinedInput-root': { color: 'white' } }}
            />
            <TextField
              label="Password"
              variant="outlined"
              fullWidth
              type="password"
              value={config.password}
              onChange={(e) => setConfig({ ...config, password: e.target.value })}
              InputProps={{
                startAdornment: <InputAdornment position="start"><Lock sx={{ color: 'primary.main' }} /></InputAdornment>,
              }}
              sx={{ '& .MuiOutlinedInput-root': { color: 'white' } }}
            />

            {error && (
              <Typography variant="caption" color="error" sx={{ textAlign: 'center' }}>
                {error}
              </Typography>
            )}

            <Button 
              type="submit" 
              variant="contained" 
              size="large" 
              disabled={loading}
              sx={{ 
                py: 1.5, 
                fontWeight: 700,
                background: 'linear-gradient(90deg, #0061ff 0%, #60a5fa 100%)',
                boxShadow: '0 8px 16px rgba(0, 97, 255, 0.3)'
              }}
            >
              {loading ? 'Connecting...' : 'Connect Now'}
            </Button>
          </Stack>
        </form>
      </Paper>
    </Box>
  );
};

export default Login;
