'use client';

import * as React from 'react';
import RouterLink from 'next/link';
import Button from '@mui/material/Button';
import Link from '@mui/material/Link';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import { Eye as EyeIcon } from '@phosphor-icons/react/dist/ssr/Eye';
import { EyeSlash as EyeSlashIcon } from '@phosphor-icons/react/dist/ssr/EyeSlash';
import { paths } from '@/paths';
import { TextField } from '@mui/material';
import axios, { AxiosError } from "axios";
import { Toaster, toast } from "react-hot-toast";
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import IconButton from '@mui/material/IconButton';
import InputAdornment from '@mui/material/InputAdornment';
import { firebaseMessagingService } from '@/services/firebase-messaging.service';

interface AdminData {
  _id: string;
}

interface LoginResponseData {
  AuthToken: string;
  admin_data: AdminData;
}

interface LoginResponse {
  data: LoginResponseData;
  message: string;
}

const liveUrl = process.env.NEXT_PUBLIC_LIVE_API_URL

console.log("liveUrl", liveUrl)

export function SignInForm(): React.JSX.Element {

  const [emailAddress, setEmailAddress] = useState<string>(""); 
  const [password, setPassword] = useState<string>("");
  const [showPassword, setShowPassword] = useState<boolean>(false);
  const [deviceToken, setDeviceToken] = useState<string | null>(null);
  const router = useRouter();

  // Get Firebase FCM token on component mount
  useEffect(() => {
    const getFirebaseToken = async () => {
      try {
        // Initialize Firebase messaging service
        await firebaseMessagingService.initialize();
        
        // Get FCM token
        const fcmToken = await firebaseMessagingService.getFCMToken();
        
        if (fcmToken) {
          console.log('FCM Token obtained:', fcmToken);
          setDeviceToken(fcmToken);
          // Store token in localStorage for future use
          localStorage.setItem('fcm_token', fcmToken);
        } else {
          console.log('No FCM token available');
          // Fallback: generate a unique token for this browser session
          const browserToken = `web_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
          localStorage.setItem('fcm_token', browserToken);
          setDeviceToken(browserToken);
        }
      } catch (error) {
        console.error('Error getting FCM token:', error);
        // Fallback: generate a unique token for this browser session
        const browserToken = `web_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
        localStorage.setItem('fcm_token', browserToken);
        setDeviceToken(browserToken);
      }
    };
    
    getFirebaseToken();
  }, []);

  const handlePassword = (event: React.ChangeEvent<HTMLInputElement>) => {
    setPassword(event.target.value);
  };

  const handleEmail = (event: React.ChangeEvent<HTMLInputElement>) => {
    setEmailAddress(event.target.value);
  };

  const handleClickShowPassword = () => {
    setShowPassword(!showPassword);
  };

  const handleMouseDownPassword = (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
  };

  const handleError = (msg: string) => {
    toast.error(msg);
  };

  const handleSuccess = (msg: string) => {
    toast.success(msg);
  };

  const submitResult = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    try {
      if (emailAddress === "" || password === "") {
        handleError("Please fill all fields");
        return;
      }

      // Add email format validation
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(emailAddress)) {
        handleError("Please enter a valid email");
        return;
      }

      // Make sure to correctly type the response
      const response = await axios.post<LoginResponse>(`${liveUrl}/api/v1/loginAdmin`, {
        emailAddress,
        password,
        accountType: "Admin",
        deviceToken: deviceToken, // Add device token for push notifications
        deviceType: "web", // Add device type for web dashboard
      });

      const { AuthToken, admin_data } = response.data.data;  // Ensure proper destructuring

      const fetchToken = localStorage.getItem("token");

      if (fetchToken) {
        localStorage.removeItem("token");
      }

      // Since we have strict typing, we ensure AuthToken and _id are strings
      localStorage.setItem("token", AuthToken);
      localStorage.setItem("AdminId", admin_data._id);

      handleSuccess("Login Successfully");

      router.push("/dashboard");
    } catch (e) {
      // Properly type Axios error
      if (axios.isAxiosError(e)) {
        const axiosError = e as AxiosError<{ message: string }>;
        handleError("Email or password is incorrect");
      } else {
        handleError("Email or password is incorrect");
      }
    }
  };

  return (
    <Stack spacing={4} alignItems="center" sx={{ textAlign: 'center', px: 3, py: 6, bgcolor: 'white', borderRadius: 2, boxShadow: '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)' }}>
      <Toaster />
      <Stack spacing={1} mb={2}>
        <Typography variant="h4" sx={{ fontWeight: 'bold', color: '#1f2937' }}>Welcome Back</Typography>
        <Typography variant="body1" sx={{ color: '#6b7280' }}>Sign in to your account</Typography>
      </Stack>
      <form onSubmit={submitResult}>
        <Stack spacing={3}>
          <TextField
            fullWidth
            value={emailAddress}
            onChange={handleEmail}
            label="Email Address"
            variant="outlined"
            sx={{
              input: { color: '#1f2937' },
              borderRadius: 2,
              '& .MuiOutlinedInput-root': {
                borderRadius: 2,
                backgroundColor: '#f9fafb',
                '& fieldset': {
                  borderColor: '#d1d5db',
                },
                '&.Mui-focused fieldset': {
                  borderColor: '#3b82f6',
                },
              },
              '& .MuiInputLabel-root': {
                color: '#6b7280',
              },
              '& .MuiInputLabel-root.Mui-focused': {
                color: '#3b82f6',
              },
            }}
          />
          <TextField
            fullWidth
            value={password}
            onChange={handlePassword}
            label="Password"
            variant="outlined"
            type={showPassword ? 'text' : 'password'}
            InputProps={{
              endAdornment: (
                <InputAdornment position="end">
                  <IconButton
                    aria-label="toggle password visibility"
                    onClick={handleClickShowPassword}
                    onMouseDown={handleMouseDownPassword}
                    edge="end"
                    sx={{ color: '#6b7280' }}
                  >
                    {showPassword ? <EyeSlashIcon /> : <EyeIcon />}
                  </IconButton>
                </InputAdornment>
              ),
            }}
            sx={{
              input: { color: '#1f2937' },
              borderRadius: 2,
              '& .MuiOutlinedInput-root': {
                borderRadius: 2,
                backgroundColor: '#f9fafb',
                '& fieldset': {
                  borderColor: '#d1d5db',
                },
                '&.Mui-focused fieldset': {
                  borderColor: '#3b82f6',
                },
              },
              '& .MuiInputLabel-root': {
                color: '#6b7280',
              },
              '& .MuiInputLabel-root.Mui-focused': {
                color: '#3b82f6',
              },
            }}
          />
          <Link component={RouterLink} href={paths.auth.resetPassword} sx={{ color: '#3b82f6', textDecoration: 'none', my: 1 }} variant="subtitle2">
            Forgot password?
          </Link>
          <Button
            fullWidth
            type="submit"
            variant="contained"
            sx={{
              bgcolor: '#3b82f6',
              color: 'white',
              fontWeight: 'bold',
              py: 1.5,
              borderRadius: 5,
              boxShadow: '0 4px 14px 0 rgba(59, 130, 246, 0.3)',
              '&:hover': {
                bgcolor: '#2563eb',
              },
            }}
          >
            Sign in
          </Button>
        </Stack>
      </form>
    </Stack>
  );
}
