import { useEffect, useState } from "react";
import Checkbox from "@/Components/Checkbox";
import GuestLayout from "@/Layouts/GuestLayout";
import InputError from "@/Components/InputError";
import InputLabel from "@/Components/InputLabel";
import PrimaryButton from "@/Components/PrimaryButton";
import TextInput from "@/Components/TextInput";
import { Head, Link, useForm } from "@inertiajs/react";
import LeftImage from "@/img/leftImage.png";

const API_URL = import.meta.env.VITE_API_URL;

export default function Login({ status, canResetPassword }) {
    const [activeTab, setActiveTab] = useState("pin"); // State to track active tab
    const [selectedCompany, setSelectedCompany] = useState("");
    const [selectedBranch, setSelectedBranch] = useState("");
    const [companyData, setCompanies] = useState([]);
    const [branchData, setbranchData] = useState([]);
    const { data, setData, post, processing, errors, reset } = useForm({
        user_pin: "", // Add a new field for PIN
        email: "",
        password: "",
        remember: false,
        company_id: "",
        branch_id: "",
    });

    useEffect(() => {
        return () => {
            reset("password", "user_pin"); // Reset both password and PIN fields
        };
    }, []);

    const submit = (e) => {
        e.preventDefault();
        if (activeTab === "pin") {
            // Handle PIN-based login
            post(route("login.pin")); 
        } else {
            // Handle email/password-based login
            post(route("login"));
        }
    };

    // Handle company selection change
    const handleCompanyChange = (e) => {
        const companyId = e.target.value;
        setSelectedCompany(companyId);
        setData("company_id", companyId); // Update the data object with the selected company ID
        setSelectedBranch(""); // Reset branch selection
        if (companyId) {
            handleGetBranchData(companyId); // Fetch branches for the selected company
        } else {
            setbranchData([]); // Clear branch data if no company is selected
            setData("branch_id", ""); // Reset branch ID in the data object
        }
    };
    
    const handleBranchChange = (e) => {
        const branchId = e.target.value;
        setSelectedBranch(branchId);
        setData("branch_id", branchId); // Update the data object with the selected branch ID
    };

    const handleGetData = async () => {
        try {
            const response = await axios.get(`${API_URL}/company/index`);
            setCompanies(response.data);
        } catch (error) {
            console.error("Error fetching company data:", error);
        }
    };

    const handleGetBranchData = async (companyId) => {
        try {
            const response = await axios.get(`${API_URL}/companyBranch/show/${companyId}`);
            setbranchData(response.data);
        } catch (error) {
            console.error("Error fetching branch data:", error);
            setSelectedCompany(""); // Reset company selection if an error occurs
        }
    };

    useEffect(() => {
        handleGetData();
    }, []);

    return (
        <GuestLayout>
            <Head title="Log in" />

            <div className="relative min-h-screen flex items-center justify-center bg-gradient-to-r from-blue-100 to-blue-400 overflow-hidden">
                {/* Circle Shapes using SVG */}
                <div className="absolute inset-0">
                    {/* Existing SVG circles */}
                </div>

                {/* Main Login Card */}
                <div className="bg-sky-100 shadow-lg rounded-2xl overflow-hidden w-full max-w-4xl relative z-10">
                    <div className="grid grid-cols-1 md:grid-cols-2">
                        {/* Left Side Image */}
                        <div className="hidden md:flex items-center justify-center">
                            <img
                                src={LeftImage}
                                alt="Login Illustration"
                                className="w-[380px] h-[450px] " // Fixed size using TailwindCSS
                            />
                        </div>

                        {/* Right Side Form */}
                        <div className="flex flex-col items-center justify-center p-6 md:p-10 w-full">
                            <div className="w-full max-w-md space-y-6">
                                <h2 className="text-3xl font-bold text-gray-900">
                                    Welcome
                                </h2>
                                <p className="text-gray-600">
                                    Sign in to your account
                                </p>

                                {/* Tab Buttons */}
                                <div className="flex space-x-4 border-b border-gray-300">
                                    <button
                                        type="button"
                                        className={`pb-2 text-sm font-medium ${
                                            activeTab === "pin"
                                                ? "border-b-2 border-indigo-500 text-indigo-600"
                                                : "text-gray-600 hover:text-gray-800"
                                        }`}
                                        onClick={() => setActiveTab("pin")}
                                    >
                                        PIN Login
                                    </button>
                                    <button
                                        type="button"
                                        className={`pb-2 text-sm font-medium ${
                                            activeTab === "email"
                                                ? "border-b-2 border-indigo-500 text-indigo-600"
                                                : "text-gray-600 hover:text-gray-800"
                                        }`}
                                        onClick={() => setActiveTab("email")}
                                    >
                                        Email Login
                                    </button>
                                </div>

                                {/* Conditional Form Content */}
                                <form onSubmit={submit} className="space-y-4">
                                    {activeTab === "pin" ? (
                                        // PIN Login Fields
                                        <>
                                            <div>
                                                <InputLabel
                                                    htmlFor="pin"
                                                    value="Enter PIN"
                                                />
                                                <TextInput
                                                    id="pin"
                                                    type="text" // Use text instead of number
                                                    name="user_pin"
                                                    value={data.user_pin}
                                                    className="mt-1 block w-full"
                                                    autoComplete="off"
                                                    onChange={(e) => {
                                                        // Allow only numeric input
                                                        if (
                                                            /^\d*$/.test(
                                                                e.target.value
                                                            )
                                                        ) {
                                                            setData(
                                                                "user_pin",
                                                                e.target.value
                                                            );
                                                        }
                                                    }}
                                                />
                                                <InputError
                                                    message={errors.user_pin}
                                                    className="mt-2"
                                                />
                                            </div>
                                            {/* Company Dropdown */}
                                            <div className="mb-4">
                                                <label
                                                    htmlFor="company"
                                                    className="block text-sm font-medium text-gray-700"
                                                >
                                                    Company
                                                </label>
                                                <select
                                                    id="company"
                                                    name="company_id"
                                                    value={selectedCompany || data.company_id}
                                                    className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                                    onChange={
                                                        handleCompanyChange
                                                    }
                                                >
                                                    <option value="">
                                                        -- Select Company --
                                                    </option>
                                                    {companyData.map(
                                                        (company) => (
                                                            <option
                                                                key={company.id}
                                                                value={
                                                                    company.id
                                                                }
                                                            >
                                                                {company.name}
                                                            </option>
                                                        )
                                                    )}
                                                </select>
                                                <InputError
                                                    message={errors.company_id}
                                                    className="mt-2"
                                                />
                                            </div>
                                            {/* Branch/Office Section Dropdown */}
                                            <div className="mb-4">
                                                <label
                                                    htmlFor="branch"
                                                    className="block text-sm font-medium text-gray-700"
                                                >
                                                    Branch / Office Section
                                                </label>
                                                <select
                                                    id="branch"
                                                    name="branch_id"
                                                    value={selectedBranch || data.branch_id}
                                                    className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                                    onChange={
                                                        handleBranchChange
                                                    }
                                                    disabled={!selectedCompany} // Disable if no company is selected
                                                >
                                                    <option value="">
                                                        -- Select Branch --
                                                    </option>
                                                    {branchData.map(
                                                        (branch) => (
                                                            <option
                                                                key={branch.id}
                                                                value={
                                                                    branch.id
                                                                }
                                                            >
                                                                {
                                                                    branch.branchName
                                                                }
                                                            </option>
                                                        )
                                                    )}
                                                </select>
                                                 <InputError
                                                    message={errors.branch_id}
                                                    className="mt-2"
                                                />
                                            </div>
                                        </>
                                    ) : (
                                        // Email/Password Login Fields
                                        <>
                                            <div>
                                                <InputLabel
                                                    htmlFor="email"
                                                    value="Email"
                                                />
                                                <TextInput
                                                    id="email"
                                                    type="email"
                                                    name="email"
                                                    value={data.email}
                                                    className="mt-1 block w-full"
                                                    autoComplete="username"
                                                    isFocused={true}
                                                    onChange={(e) =>
                                                        setData(
                                                            "email",
                                                            e.target.value
                                                        )
                                                    }
                                                />
                                                <InputError
                                                    message={errors.email}
                                                    className="mt-2"
                                                />
                                            </div>

                                            <div>
                                                <InputLabel
                                                    htmlFor="password"
                                                    value="Password"
                                                />
                                                <TextInput
                                                    id="password"
                                                    type="password"
                                                    name="password"
                                                    value={data.password}
                                                    className="mt-1 block w-full"
                                                    autoComplete="current-password"
                                                    onChange={(e) =>
                                                        setData(
                                                            "password",
                                                            e.target.value
                                                        )
                                                    }
                                                />
                                                <InputError
                                                    message={errors.password}
                                                    className="mt-2"
                                                />

                                                {/* {canResetPassword && (
                                                    <div className="text-right mt-2">
                                                        <Link href={route('password.request')} className="text-sm text-indigo-600 hover:text-indigo-900">
                                                            Forget password?
                                                        </Link>
                                                    </div>
                                                )} */}
                                            </div>

                                            {/* Company Dropdown */}
                                            <div className="mb-4">
                                                <label
                                                    htmlFor="company"
                                                    className="block text-sm font-medium text-gray-700"
                                                >
                                                    Company
                                                </label>
                                                <select
                                                    id="company"
                                                    name="company"
                                                    value={selectedCompany}
                                                    className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                                    onChange={
                                                        handleCompanyChange
                                                    }
                                                >
                                                    <option value="">
                                                        -- Select Company --
                                                    </option>
                                                    {companyData.map(
                                                        (company) => (
                                                            <option
                                                                key={company.id}
                                                                value={
                                                                    company.id
                                                                }
                                                            >
                                                                {company.name}
                                                            </option>
                                                        )
                                                    )}
                                                </select>
                                                <InputError
                                                    message={errors.company_id}
                                                    className="mt-2"
                                                />
                                            </div>
                                            {/* Branch/Office Section Dropdown */}
                                            <div className="mb-4">
                                                <label
                                                    htmlFor="branch"
                                                    className="block text-sm font-medium text-gray-700"
                                                >
                                                    Branch / Office Section
                                                </label>
                                                <select
                                                    id="branch"
                                                    name="branch"
                                                    value={selectedBranch}
                                                    className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                                                    onChange={
                                                        handleBranchChange
                                                    }
                                                    disabled={!selectedCompany} // Disable if no company is selected
                                                >
                                                    <option value="">
                                                        -- Select Branch --
                                                    </option>
                                                    {branchData.map(
                                                        (branch) => (
                                                            <option
                                                                key={branch.id}
                                                                value={
                                                                    branch.id
                                                                }
                                                            >
                                                                {
                                                                    branch.branchName
                                                                }
                                                            </option>
                                                        )
                                                    )}
                                                </select>
                                                <InputError
                                                    message={errors.branch_id}
                                                    className="mt-2"
                                                />
                                            </div>
                                        </>
                                    )}

                                    <div className="flex flex-col justify-between">
                                        <div>
                                            {/* Submit Button */}
                                            <PrimaryButton
                                                className="w-full py-3 flex justify-center items-center text-center"
                                                disabled={processing}
                                            >
                                                Log in
                                            </PrimaryButton>
                                        </div>
                                        <div className="flex justify-between mt-5">
                                            {/* Sign Up Link */}
                                            {canResetPassword && (
                                                <Link
                                                    href={route("register")}
                                                    className="w-full py-3 text-center bg-indigo-100 text-indigo-600 hover:bg-indigo-200 font-semibold rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                                >
                                                    Sign up
                                                </Link>
                                            )}
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </GuestLayout>
    );
}
