import { FormEvent, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { apiGet } from "../lib/api";
import type { DashboardOverview, LookupResult } from "../lib/types";

function formatDate(value: string) {
  return new Intl.DateTimeFormat("de-DE", {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(new Date(value));
}

function routeForSample(sampleId: string, routeSegment: string) {
  return `/samples/${sampleId}/${routeSegment}`;
}

const STEP_LABELS: Record<string, string> = {
  ANAMNESIS: "Anamnese",
  ANTIBIOGRAM: "Antibiogramm",
  THERAPY: "Therapie",
  COMPLETED: "Abgeschlossen",
};

export default function HomePage() {
  const navigate = useNavigate();
  const [dashboard, setDashboard] = useState<DashboardOverview | null>(null);
  const [sampleNumber, setSampleNumber] = useState("");
  const [message, setMessage] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [showValidation, setShowValidation] = useState(false);

  useEffect(() => {
    async function loadDashboard() {
      try {
        const response = await apiGet<DashboardOverview>("/dashboard");
        setDashboard(response);
      } finally {
        setLoading(false);
      }
    }

    void loadDashboard();
  }, []);

  async function handleLookup(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setShowValidation(true);
    if (!sampleNumber.trim()) {
      setMessage("Bitte eine Probennummer eingeben.");
      return;
    }

    try {
      const response = await apiGet<LookupResult>(`/dashboard/lookup/${sampleNumber.trim()}`);
      if (!response.found || !response.sampleId || !response.routeSegment) {
        setMessage(response.message);
        return;
      }
      setMessage(null);
      navigate(routeForSample(response.sampleId, response.routeSegment));
    } catch (lookupError) {
      setMessage((lookupError as Error).message);
    }
  }

  return (
    <div className="page-stack">
      <section className="hero-card">
        <div>
          <p className="eyebrow">Startseite</p>
          <h3>Bearbeitungsstand sofort finden</h3>
          <p className="muted-text">
            Eine bekannte Probennummer oeffnet direkt den passenden Arbeitsschritt.
          </p>
        </div>

        <form className={`hero-card__form ${showValidation ? "show-validation" : ""}`} onSubmit={handleLookup}>
          <label className="field field--required">
            <span>Nummer</span>
            <input
              value={sampleNumber}
              onChange={(event) => setSampleNumber(event.target.value)}
              placeholder="z. B. 100203"
              inputMode="numeric"
              required
            />
          </label>
          <button type="submit" className="accent-button">
            Probe öffnen
          </button>
        </form>

        {message ? <div className="alert alert--error">{message}</div> : null}
      </section>

      <section className="metrics-grid">
        <article className="metric-card">
          <span className="metric-card__label">Naechste Nummer</span>
          <strong>{dashboard?.nextSampleNumber ?? "..."}</strong>
        </article>
        <article className="metric-card">
          <span className="metric-card__label">Offene Proben</span>
          <strong>{dashboard?.openSamples ?? "..."}</strong>
        </article>
        <article className="metric-card">
          <span className="metric-card__label">Heute abgeschlossen</span>
          <strong>{dashboard?.completedToday ?? "..."}</strong>
        </article>
      </section>

      <section className="section-card">
        <div className="section-card__header">
          <div>
            <p className="eyebrow">Arbeitsvorrat</p>
            <h3>Zuletzt bearbeitete Proben</h3>
          </div>
        </div>

        {loading ? (
          <div className="empty-state">Dashboard wird geladen ...</div>
        ) : dashboard?.recentSamples.length ? (
          <div className="table-shell">
            <table className="data-table">
              <thead>
                <tr>
                  <th>Probe</th>
                  <th>Landwirt</th>
                  <th>Kuh</th>
                  <th>Typ</th>
                  <th>Status</th>
                  <th>Aktualisiert</th>
                  <th />
                </tr>
              </thead>
              <tbody>
                {dashboard.recentSamples.map((sample) => (
                  <tr key={sample.id}>
                    <td>{sample.sampleNumber}</td>
                    <td>{sample.farmerName}</td>
                    <td>{sample.cowLabel}</td>
                    <td>{sample.sampleKind === "DRY_OFF" ? "Trockensteller" : "Laktation"}</td>
                    <td>
                      <span className={`status-pill status-pill--${sample.currentStep.toLowerCase()}`}>
                        {STEP_LABELS[sample.currentStep]}
                      </span>
                    </td>
                    <td>{formatDate(sample.updatedAt)}</td>
                    <td>
                      <button
                        type="button"
                        className="table-link"
                        onClick={() =>
                          navigate(
                            routeForSample(
                              sample.id,
                              sample.currentStep === "ANTIBIOGRAM"
                                ? "antibiogram"
                                : sample.currentStep === "THERAPY" || sample.currentStep === "COMPLETED"
                                  ? "therapy"
                                  : "anamnesis",
                            ),
                          )
                        }
                      >
                        Öffnen
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div className="empty-state">Noch keine Proben vorhanden.</div>
        )}
      </section>
    </div>
  );
}
