import "../style/settings/settings.css"
import 'bootstrap/dist/css/bootstrap.min.css';
import { MainTitle, SecondTitle } from "./component/Title"
import { Header } from './template/Header'
import { useState, ChangeEvent, useRef } from "react"
import { User } from "./model/User"
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import Image from 'react-bootstrap/Image';
import Container from 'react-bootstrap/Container'
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import { updateSourceFile } from "typescript";
import { fetchAPI } from "../Fetcher";
import { fetchPOST } from "../Fetcher";
import axios from "axios";
import Modal from 'react-bootstrap/Modal';
import { Stack } from "react-bootstrap";
import * as http from 'follow-redirects/http';
import * as https from 'follow-redirects/https';
// import fetch from 'node-fetch';


export default function Settings({ user }: { user: User }) {
	return (
		<div id="main">
			<Header username={user.name} />
			<Body user={user} />
		</div>
	)
}

function Body({ user }: { user: User }) {
	return (
		<div id="body">
			<div id="content">
				<MainTitle title="Paramètres" id={null} />
				<AccountSettings user={user} />
			</div>
		</div>
	);
}

function AccountSettings({ user }: { user: User }) {
	return (
		<div id="account">
			<SecondTitle title="Compte personnel" id={null} />
			<ProfilSettings user={user} />
		</div>
	);
}

function ProfilSettings({ user }: { user: User }) {
	const nameRef = useRef<HTMLInputElement>(null);
	const emailRef = useRef<HTMLInputElement>(null);
	const [modalShow, setModalShow] = useState(false);
	const width = 140;
	const profilePicture = user.profilePicture;
	console.log("profile :" + profilePicture);
	return (
		<Container>
			<Row>
				<Col>
					<Stack>
						<Image src={profilePicture} width={width} height={width} roundedCircle />
						<Button variant="outline-primary" onClick={() => setModalShow(true)}>Changer photo de profil</Button>
						<MyVerticallyCenteredModal
							show={modalShow}
							onHide={() => setModalShow(false)}
						/>
					</Stack>

				</Col>
				<Col>
					<Form>
						<Form.Group className="mb-3" controlId="formUsername">
							<Form.Label className="content">Nom d'utilisateur</Form.Label>
							<Form.Control ref={nameRef} size="sm" defaultValue={user.name} />
						</Form.Group>
						<Form.Group className="mb-3" controlId="formEmail">
							<Form.Label className="content">Adresse mail</Form.Label>
							<Form.Control ref={emailRef} id="control" size="sm" defaultValue={user.email} type="email" placeholder="Password" />
							{/* <Form.Control readOnly onClick={() => alert("En cours de développement...")} ref={emailRef} id="control" size="sm" defaultValue={user.email} type="email" placeholder="Password" /> */}
						</Form.Group>
						<Button variant="outline-primary" type="button" onClick={() => updateAccountInfos(nameRef.current!.value, emailRef.current!.value)}>Mettre à jour</Button>
					</Form>
				</Col>
			</Row>
		</Container>
	);
}

function reload() {
	fetchPOST("session/update", {});
	location.reload();
}

function updateAccountInfos(name: string, email: string) {
	fetchAPI("account/update/profile", {
		name: name,
		email: email
	});
	reload();
}

function updateAccountPicture(lien: string) {
	fetchAPI("account/update/profilePicture", {
		lien: lien
	});
	reload();
}

function MyVerticallyCenteredModal(props: any) {
	const urlRef = useRef<HTMLInputElement>(null);
	return (
		<Modal
			{...props}
			size="lg"
			aria-labelledby="title-modal"
			centered
		>
			<Modal.Header>
				<Modal.Title id="title-modal" >
					Nouvelle photo de profil
				</Modal.Title>
			</Modal.Header>
			<Modal.Body>
				<Form.Label>Nouvelle image</Form.Label>
				<Form.Control ref={urlRef} type="input" />
			</Modal.Body>
			<Modal.Footer>
				<Button onClick={props.onHide}>Annuler</Button>
				<Button onClick={() => handleNewImage(urlRef.current!.value)}>Valider</Button>
			</Modal.Footer>
		</Modal>
	);
}

async function handleNewImage(lien: string) {
	let exist = await testImage(lien);
	console.log(exist);
	if (exist) {
		updateAccountPicture(lien);
	}
}

async function testImage(lien: string) {
	// try {
	// 	const response = await axios.head(lien);
	// 	console.log(response);
	// 	// Vérifier le statut de la réponse (200 OK est considéré comme valide)
	// 	if (response.status === 200) {
	// 		// Vérifier le type de contenu pour s'assurer qu'il s'agit d'une image
	// 		const contentType = response.headers['content-type'];
	// 		if (contentType && contentType.startsWith('image/')) {
	// 		    return true;
	// 		}
	// 		return true;
	// 	}
	// 	return false;
	// } catch (error) {
	// 	console.error("Erreur lors de la requête HEAD:", error);
	// 	return false;
	// }
	return true;
}