import { useNavigate } from "react-router-dom";
import SampleSearchResultsSection from "../components/SampleSearchResultsSection";
import { apiGet } from "../lib/api";
import type { LookupResult, PortalSampleRow } from "../lib/types";
import { useState } from "react";

function routeForLookup(result: LookupResult) {
  return result.sampleId && result.routeSegment ? `/samples/${result.sampleId}/${result.routeSegment}` : null;
}

export default function SearchCalendarPage() {
  const navigate = useNavigate();
  const [selectedDate, setSelectedDate] = useState("");
  const [samples, setSamples] = useState<PortalSampleRow[]>([]);
  const [message, setMessage] = useState<string | null>(null);
  const [resultLabel, setResultLabel] = useState("Bitte Datum auswaehlen");

  async function handleDateChange(nextDate: string) {
    setSelectedDate(nextDate);
    if (!nextDate) {
      setSamples([]);
      setMessage(null);
      setResultLabel("Bitte Datum auswaehlen");
      return;
    }

    try {
      const rows = await apiGet<PortalSampleRow[]>(
        `/portal/search/by-date?date=${encodeURIComponent(nextDate)}`,
      );
      setSamples(rows);
      setResultLabel(`Erfasste Proben am ${nextDate.split("-").reverse().join(".")}`);
      setMessage(rows.length ? null : "An diesem Tag wurden keine Proben erfasst.");
    } catch (dateError) {
      setSamples([]);
      setResultLabel("Keine Treffer");
      setMessage((dateError as Error).message);
    }
  }

  async function openSample(sampleNumber: number) {
    try {
      const result = await apiGet<LookupResult>(`/dashboard/lookup/${sampleNumber}`);
      const target = routeForLookup(result);
      if (!result.found || !target) {
        setMessage(result.message);
        return;
      }
      navigate(target);
    } catch (openError) {
      setMessage((openError as Error).message);
    }
  }

  return (
    <div className="page-stack">
      <section className="section-card section-card--hero">
        <div>
          <p className="eyebrow">Suche | Kalendar</p>
          <h3>Proben nach Erfassungsdatum finden</h3>
          <p className="muted-text">
            Waehle einen Tag im Kalendar aus, um alle an diesem Datum erfassten Proben in der Liste zu sehen.
          </p>
        </div>

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

      <section className="section-card">
        <label className="field field--required">
          <span>Kalendar</span>
          <input
            type="date"
            value={selectedDate}
            onChange={(event) => void handleDateChange(event.target.value)}
            required
          />
        </label>
      </section>

      <SampleSearchResultsSection
        eyebrow="Suchergebnisse"
        title={resultLabel}
        emptyText="Bitte ein Datum im Kalendar auswaehlen."
        samples={samples}
        onOpen={(sampleNumber) => void openSample(sampleNumber)}
      />
    </div>
  );
}
