"use client";

import { FormEvent, useMemo, useState } from "react";
import styles from "./CarbonCalculator.module.css";
import { checkCarbonAction } from "@/app/actions/carbon-check";
import Badge from "@/components/Badge/Badge";

const STATUS = {
  IDLE: "IDLE",
  LOADING: "LOADING",
  SUCCESS: "SUCCESS",
  ERROR: "ERROR",
} as const;

type StatusType = (typeof STATUS)[keyof typeof STATUS];

const CarbonCalculator = () => {
  const [url, setUrl] = useState("");
  const [status, setStatus] = useState<StatusType>(STATUS.IDLE);
  const [message, setMessage] = useState("");
  const [result, setResult] = useState<{
    pageSizeKb: number;
    estimatedCo2Milligrams: number;
    sustainabilityRating?: string;
    checkedUrl: string;
  } | null>(null);

  const formatted = useMemo(() => {
    if (!result) return null;

    return {
      pageSizeKb: result.pageSizeKb.toFixed(1),
      estimatedCo2Milligrams: result.estimatedCo2Milligrams.toFixed(2),
    };
  }, [result]);

  const ratingTone = useMemo(() => {
    const rating = result?.sustainabilityRating?.toUpperCase();
    if (!rating) return "";

    if (rating.startsWith("A")) return styles.ratingA;
    if (rating.startsWith("B")) return styles.ratingB;
    if (rating.startsWith("C")) return styles.ratingC;
    if (rating.startsWith("D")) return styles.ratingD;
    if (rating.startsWith("E")) return styles.ratingE;
    return styles.ratingF;
  }, [result?.sustainabilityRating]);

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

    if (!url.trim()) {
      setStatus(STATUS.ERROR);
      setMessage("Please enter a website URL");
      setResult(null);
      return;
    }

    setStatus(STATUS.LOADING);
    setMessage("");
    setResult(null);

    try {
      const response = await checkCarbonAction(url);

      if (!response.ok) {
        setStatus(STATUS.ERROR);
        setMessage(response.error || "Unable to calculate carbon impact.");
        return;
      }

      setStatus(STATUS.SUCCESS);
      setResult({
        pageSizeKb: response.pageSizeKb,
        estimatedCo2Milligrams: response.estimatedCo2Milligrams,
        sustainabilityRating: response.sustainabilityRating,
        checkedUrl: response.checkedUrl,
      });
      setMessage("Estimate generated for this page load.");
    } catch {
      setStatus(STATUS.ERROR);
      setMessage("Unable to calculate carbon impact right now. Please try again.");
    }
  };

  return (
    <div className={styles.calculator}>
      <form className={styles.form} onSubmit={handleSubmit}>
        <label htmlFor="carbon-calculator-url" className="sr-only">
          Website URL
        </label>
        <input
          id="carbon-calculator-url"
          name="carbon-calculator-url"
          type="text"
          placeholder="Enter website URL (e.g. example.com)"
          value={url}
          onChange={(event) => setUrl(event.target.value)}
          className={styles.input}
          autoCapitalize="off"
          autoCorrect="off"
          spellCheck={false}
          inputMode="url"
          data-lpignore="true"
          data-form-type="other"
          required
        />
        <button
          type="submit"
          className={styles.submit}
          disabled={status === STATUS.LOADING}
          aria-label="Calculate website carbon impact"
        >
          {status === STATUS.LOADING ? (
            "..."
          ) : (
            <Badge aria-label="Submit carbon calculator">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                height="24"
                viewBox="0 -960 960 960"
                width="24"
              >
                <path d="M647-440H160v-80h487L423-744l57-56 320 320-320 320-57-56 224-224Z" />
              </svg>
            </Badge>
          )}
        </button>
      </form>

      {status !== STATUS.IDLE && (
        <p
          className={[styles.status, status === STATUS.ERROR ? styles.error : ""].join(" ")}
          role="status"
          aria-live="polite"
        >
          {message}
        </p>
      )}

      {status === STATUS.SUCCESS && result && formatted && (
        <div className={styles.results}>
          <div className={styles.topRow}>
            <div className={styles.impact}>
              <span className={styles.eyebrow}>Estimated Carbon Impact</span>
              <strong className={styles.impactValue}>
                {formatted.estimatedCo2Milligrams} mg CO2e
              </strong>
            </div>

            {result.sustainabilityRating ? (
              <div className={[styles.ratingCard, ratingTone].join(" ")}>
                <span className={styles.ratingLabel}>Rating</span>
                <strong className={styles.ratingValue}>
                  {result.sustainabilityRating}
                </strong>
              </div>
            ) : null}
          </div>

          <div className={styles.chips}>
            <div className={[styles.chip, styles.pageSizeChip].join(" ")}>
              <span className={styles.chipLabel}>Page size</span>
              <strong className={styles.chipValue}>{formatted.pageSizeKb} KB</strong>
            </div>
          </div>

          <p className={styles.meta}>Source page: {result.checkedUrl}</p>
          <p className={styles.meta}>
            Estimate from CO2.js using transferred page bytes for one page load.
          </p>
        </div>
      )}
    </div>
  );
};

export default CarbonCalculator;
