import { useMemo, useState } from "react";
import { Droplets, Gauge, Timer } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import {
  CROP_OPTIONS,
  RAINFALL_OPTIONS,
  REGION_OPTIONS,
  SEASON_OPTIONS,
  VARIETIES,
  cropLabel,
  type Variety,
} from "@/data/varieties";

function DroughtRating({ score }: { score: number }) {
  return (
    <span className="flex items-center gap-1" aria-label={`Drought tolerance ${score} out of 5`}>
      {[1, 2, 3, 4, 5].map((i) => (
        <span
          key={i}
          aria-hidden="true"
          className={`h-1.5 w-4 rounded-full ${i <= score ? "bg-primary" : "bg-border"}`}
        />
      ))}
      <span className="ml-1 text-xs font-semibold text-muted-foreground">{score}/5</span>
    </span>
  );
}

function VarietyCard({ v }: { v: Variety }) {
  return (
    <li className="rounded-xl border border-border bg-card p-5 shadow-card transition-all hover:-translate-y-0.5 hover:shadow-lift">
      <div className="flex items-start justify-between gap-3">
        <div>
          <h3 className="font-display text-lg font-bold">{v.name}</h3>
          <p className="mt-0.5 text-xs font-semibold uppercase tracking-wider text-primary">{cropLabel(v.crop)}</p>
        </div>
        <span className="rounded-full bg-[#009F4F] px-3 py-0.5 text-xs font-semibold text-white shadow-2xs">
          Certified
        </span>
      </div>

      <dl className="mt-4 grid grid-cols-2 gap-3 text-sm">
        <div>
          <dt className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <Timer aria-hidden="true" className="size-3.5" /> Maturity
          </dt>
          <dd className="mt-0.5 font-semibold">{v.maturityDays} days</dd>
        </div>
        <div>
          <dt className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <Gauge aria-hidden="true" className="size-3.5" /> Yield potential
          </dt>
          <dd className="mt-0.5 font-semibold">{v.yieldPotential}</dd>
        </div>
        <div className="col-span-2">
          <dt className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <Droplets aria-hidden="true" className="size-3.5" /> Drought tolerance
          </dt>
          <dd className="mt-1.5">
            <DroughtRating score={v.droughtTolerance} />
          </dd>
        </div>
      </dl>

      <p className="mt-4 border-t border-border pt-4 text-sm leading-relaxed text-muted-foreground">
        <span className="font-semibold text-foreground">Why this variety: </span>
        {v.why}
      </p>
    </li>
  );
}

export function VarietyFinder({
  droughtDefault = false,
  compact = false,
}: {
  droughtDefault?: boolean;
  compact?: boolean;
}) {
  const [region, setRegion] = useState("southern");
  const [rainfall, setRainfall] = useState("medium");
  const [season, setSeason] = useState("main");
  const [crop, setCrop] = useState("maize");
  const [droughtOnly, setDroughtOnly] = useState(droughtDefault);

  const results = useMemo(() => {
    const strict = VARIETIES.filter(
      (v) =>
        v.crop === crop &&
        v.regions.includes(region) &&
        v.rainfall.includes(rainfall as Variety["rainfall"][number]) &&
        v.season.includes(season as Variety["season"][number]) &&
        (!droughtOnly || v.droughtTolerance >= 4),
    );
    if (strict.length > 0) return { list: strict, relaxed: false };
    const relaxed = VARIETIES.filter(
      (v) => v.crop === crop && (!droughtOnly || v.droughtTolerance >= 4),
    );
    return { list: relaxed, relaxed: true };
  }, [crop, region, rainfall, season, droughtOnly]);

  return (
    <div className={compact ? "" : "grid gap-8 lg:grid-cols-[22rem_1fr]"}>
      <form
        aria-label="Seed variety finder"
        onSubmit={(e) => e.preventDefault()}
        className="h-fit rounded-2xl border border-border bg-card p-6 shadow-card"
      >
        <div>
          <h3 className="font-display text-lg font-bold">Match seed to your field</h3>
        </div>
        <p className="mt-2 text-sm text-muted-foreground">
          Four questions. We recommend certified varieties suited to your zone and planting window.
        </p>

        <div className="mt-6 space-y-5">
          <div>
            <Label htmlFor="vf-region">Country / region</Label>
            <Select value={region} onValueChange={setRegion}>
              <SelectTrigger id="vf-region" className="mt-1.5">
                <SelectValue placeholder="Select a region" />
              </SelectTrigger>
              <SelectContent>
                {REGION_OPTIONS.map((o) => (
                  <SelectItem key={o.value} value={o.value}>
                    {o.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="vf-rainfall">Rainfall pattern / agro-ecological zone</Label>
            <Select value={rainfall} onValueChange={setRainfall}>
              <SelectTrigger id="vf-rainfall" className="mt-1.5">
                <SelectValue placeholder="Select rainfall" />
              </SelectTrigger>
              <SelectContent>
                {RAINFALL_OPTIONS.map((o) => (
                  <SelectItem key={o.value} value={o.value}>
                    {o.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="vf-season">Season / planting window</Label>
            <Select value={season} onValueChange={setSeason}>
              <SelectTrigger id="vf-season" className="mt-1.5">
                <SelectValue placeholder="Select season" />
              </SelectTrigger>
              <SelectContent>
                {SEASON_OPTIONS.map((o) => (
                  <SelectItem key={o.value} value={o.value}>
                    {o.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="vf-crop">Crop</Label>
            <Select value={crop} onValueChange={setCrop}>
              <SelectTrigger id="vf-crop" className="mt-1.5">
                <SelectValue placeholder="Select a crop" />
              </SelectTrigger>
              <SelectContent>
                {CROP_OPTIONS.map((o) => (
                  <SelectItem key={o.value} value={o.value}>
                    {o.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="flex items-center justify-between rounded-lg bg-background border border-border px-4 py-3">
            <Label htmlFor="vf-drought" className="cursor-pointer text-sm font-medium">
              Drought-resilient varieties only
            </Label>
            <Switch id="vf-drought" checked={droughtOnly} onCheckedChange={setDroughtOnly} />
          </div>

          <Button
            type="button"
            variant="outline"
            className="w-full"
            onClick={() => {
              setRegion("southern");
              setRainfall("medium");
              setSeason("main");
              setCrop("maize");
              setDroughtOnly(droughtDefault);
            }}
          >
            Reset selections
          </Button>
        </div>
      </form>

      <div className={compact ? "mt-8" : ""}>
        <div
          role="status"
          aria-live="polite"
          className="rounded-lg border border-border bg-secondary/60 px-4 py-3 text-sm"
        >
          {results.relaxed
            ? `No exact match for that combination. Showing ${results.list.length} ${cropLabel(crop).toLowerCase()} varieties closest to your selection.`
            : `${results.list.length} recommended ${cropLabel(crop).toLowerCase()} ${results.list.length === 1 ? "variety" : "varieties"} for your zone and planting window.`}
        </div>

        <ul className="mt-5 grid gap-5 sm:grid-cols-2">
          {results.list.map((v) => (
            <VarietyCard key={v.id} v={v} />
          ))}
        </ul>

        {results.list.length === 0 && (
          <p className="mt-6 text-sm text-muted-foreground">
            We do not yet list varieties for this combination. Contact your nearest Seed Co office for advice.
          </p>
        )}
      </div>
    </div>
  );
}
