"use client";

import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useToast } from '@/context/ToastContext';
import { useUser } from "@/context/UserContext";
import { Container, Card, Row, Col, Button, Form, FloatingLabel, Stack, Spinner } from "react-bootstrap";
import LoadingCMS from "@/components/LoadingCMS";
import { unixToDateTime } from "@/lib/function";

type FormData = {
  su_name: string;
  su_email: string;
  su_mobile: string;
  su_password: string;
  new_password: string;
};

export default function Profile() {
  const { showToast } = useToast();
  const { user, loading } = useUser();
  const [uData, setUdata] = useState<{ su_name?: string; su_email?: string; su_mobile?: string } | null>(null);
  const [lastLogin, setLastLogin] = useState<number>(0);
  const [profileLoading, setProfileLoading] = React.useState(true);

  const {
    register: registerProfile,
    handleSubmit: handleProfileSubmit,
    reset: resetProfile,
    formState: { errors: profileErrors, isSubmitting: isSubmittingProfile },
  } = useForm<FormData>();

  const {
    register: registerPassword,
    handleSubmit: handlePasswordSubmit,
    reset: resetPassword,
    formState: { errors: passwordErrors, isSubmitting: isSubmittingPassword },
  } = useForm<FormData>();

  useEffect(() => {
    const fetchProfile = async () => {
      if (!user?.id) return;
      try {
        const res = await fetch("/api/user/details", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id: user.id }),
        });
        const data = await res.json();
        if (res.ok) {
          resetProfile({
            su_name: data.su_name,
            su_email: data.su_email,
            su_mobile: data.su_mobile,
          });
          setUdata(data);
        } 
        else { showToast(data.error, "danger"); }
      } 
      catch { showToast("User details: fetching failed..", "danger"); } 
      finally { setProfileLoading(false); }
    };
    const fetchLastLogin = async () => {
      if (!user?.id) return;
      try {
        const res = await fetch("/api/user/details/log/last-login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ id: user.id }),
        });
        const data = await res.json();
        if (res.ok) {
          setLastLogin(data.sul_date || 0);
        } 
        else { showToast(data.error, "danger"); }
      } 
      catch { showToast("User Log: fetching failed..", "danger"); } 
      finally { setProfileLoading(false); }
    };
    fetchProfile();
    fetchLastLogin();
  }, [user?.id, resetProfile, showToast]);

  const handleProfileUpdate = async (data: Partial<FormData>) => {
    if (!user?.id) return;

    const res = await fetch("/api/user/update", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        id: user.id,
        su_name: data.su_name,
        callBy: "user",
        callMode: "profile",
      }),
    });

    const result = await res.json();

    if (res.ok) {
      showToast(result.message, "success");
    } else {
      showToast(result.error || "Something went wrong", "danger");
    }
  };

  const handlePasswordUpdate = async (data: Partial<FormData>) => {
    if (!user?.id) return;

    const res = await fetch("/api/user/update", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        id: user.id,
        su_password: data.su_password,
        new_password: data.new_password,
        callBy: "user",
        callMode: "password",
      }),
    });

    const result = await res.json();

    if (res.ok) {
      showToast(result.message, "success");
      resetPassword({su_password:'',new_password:''})
    } else {
      showToast(result.error || "Invalid old password", "danger");
    }
  };

  const passwordRules = {
    required: "Password is required",
    pattern: {
      value: /^(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,}$/,
      message: "Min 8 chars, 1 uppercase, 1 number, 1 special",
    },
  };

  if (loading || profileLoading) {
    return <LoadingCMS />;
  }

  return (
    <Container fluid className="py-3 py-md-5">
      <Row className="justify-content-center">
        <Col md={6}>
          <Card className="rounded-5 mb-3">
            <Card.Body>
              <div className="d-flex align-items-center">
                <i className="bi bi-person-circle display-2"></i>
                <h1 className="fs-1 m-0 flex-fill px-3">{uData?.su_name || ""}</h1>
                <div className="text-secondary d-flex flex-column text-end">
                  <b>Last Login</b>
                  <small>{unixToDateTime(lastLogin,"date")} {unixToDateTime(lastLogin,"time")}</small>
                </div>
              </div>
            </Card.Body>
          </Card>
          <Card className="rounded-5 mb-3">
            <Card.Body>
              <Form noValidate onSubmit={handleProfileSubmit(handleProfileUpdate)}>
                <Row className="g-3">
                  <Col md={12}>
                    <h3>Update Profile</h3>
                  </Col>
                  <Col md={12}>
                    <FloatingLabel label="Full Name">
                      <Form.Control
                        type="text"
                        {...registerProfile("su_name", {
                          required: "Full name is required",
                          pattern: {
                            value: /^[a-zA-Z]+ [a-zA-Z]+$/,
                            message: "Enter first and last name",
                          },
                        })}
                        isInvalid={!!profileErrors.su_name}
                        disabled={isSubmittingProfile}
                      />
                      <Form.Control.Feedback type="invalid">
                        {profileErrors.su_name?.message}
                      </Form.Control.Feedback>
                    </FloatingLabel>
                  </Col>
                  <Col md={12}>
                    <FloatingLabel label="Email address">
                      <Form.Control
                        type="email"
                        {...registerProfile("su_email", {
                          required: "Email is required",
                          pattern: {
                            value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                            message: "Invalid email format",
                          },
                        })}
                        isInvalid={!!profileErrors.su_email}
                        disabled={true}
                      />
                      <Form.Control.Feedback type="invalid">
                        {profileErrors.su_email?.message}
                      </Form.Control.Feedback>
                    </FloatingLabel>
                  </Col>
                  <Col md={12}>
                    <FloatingLabel label="Mobile">
                      <Form.Control
                        type="tel"
                        {...registerProfile("su_mobile", {
                          required: "Mobile number is required",
                          pattern: {
                            value: /^[6-9]\d{9}$/,
                            message: "Enter a valid 10-digit Indian mobile number",
                          },
                        })}
                        isInvalid={!!profileErrors.su_mobile}
                        disabled={true}
                      />
                      <Form.Control.Feedback type="invalid">
                        {profileErrors.su_mobile?.message}
                      </Form.Control.Feedback>
                    </FloatingLabel>
                  </Col>
                  <Col md={12}>
                    <Button
                      size="lg"
                      variant="outline-danger"
                      className="rounded-pill w-100"
                      type="submit"
                      disabled={isSubmittingProfile}
                    >
                      {isSubmittingProfile ? (
                        <Stack gap={2} direction="horizontal">
                          <Spinner animation="grow" size="sm" variant="danger" />
                          <Spinner animation="grow" size="sm" variant="primary" />
                          <Spinner animation="grow" size="sm" variant="success" />
                          <span>Updating...</span>
                        </Stack>
                      ) : (
                        "Update"
                      )}
                    </Button>
                  </Col>
                </Row>
              </Form>
            </Card.Body>
          </Card>
          <Card className="rounded-5 mb-3">
            <Card.Body>
              <Form noValidate onSubmit={handlePasswordSubmit(handlePasswordUpdate)}>
                <Row className="g-3">
                  <Col md={12}>
                    <h3>Update Password</h3>
                  </Col>
                  <Col md={12}>
                    <FloatingLabel label="Old Password">
                      <Form.Control
                        type="password"
                        {...registerPassword("su_password", passwordRules)}
                        isInvalid={!!passwordErrors.su_password}
                        disabled={isSubmittingPassword}
                      />
                      <Form.Control.Feedback type="invalid">
                        {passwordErrors.su_password?.message}
                      </Form.Control.Feedback>
                    </FloatingLabel>
                  </Col>
                  <Col md={12}>
                    <FloatingLabel label="New Password">
                      <Form.Control
                        type="password"
                        {...registerPassword("new_password", passwordRules)}
                        isInvalid={!!passwordErrors.new_password}
                        disabled={isSubmittingPassword}
                      />
                      <Form.Control.Feedback type="invalid">
                        {passwordErrors.new_password?.message}
                      </Form.Control.Feedback>
                    </FloatingLabel>
                  </Col>
                  <Col md={12}>
                    <Button
                      size="lg"
                      variant="outline-danger"
                      className="rounded-pill w-100"
                      type="submit"
                      disabled={isSubmittingPassword}
                    >
                      {isSubmittingPassword ? (
                        <Stack gap={2} direction="horizontal">
                          <Spinner animation="grow" size="sm" variant="danger" />
                          <Spinner animation="grow" size="sm" variant="primary" />
                          <Spinner animation="grow" size="sm" variant="success" />
                          <span>Updating...</span>
                        </Stack>
                      ) : (
                        "Update"
                      )}
                    </Button>
                  </Col>
                </Row>
              </Form>
            </Card.Body>
          </Card>
        </Col>
      </Row>
    </Container>
  );
}
