"use client";

import * as React from "react";
import { toast } from "sonner";
import {
  Loader2,
  Plus,
  MapPin,
  CalendarDays,
  Trash2,
  Save,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";

type Location = {
  id: string;
  name: string;
  address: string | null;
  collectionDays: CollectionDay[];
};

type CollectionDay = {
  id: string;
  name: string;
  dayOfWeek: number | null;
  timeStart: string | null;
  timeEnd: string | null;
  isActive: boolean;
};

const DAYS = [
  "Sunday",
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday",
  "Saturday",
];

export default function LocationsSettingsPage() {
  const [locations, setLocations] = React.useState<Location[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [newLocName, setNewLocName] = React.useState("");
  const [newLocAddress, setNewLocAddress] = React.useState("");
  const [adding, setAdding] = React.useState(false);

  const fetchData = React.useCallback(async () => {
    try {
      const res = await fetch("/api/org/locations");
      if (res.ok) {
        const data = await res.json();
        setLocations(data.locations || []);
      }
    } catch {} finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleAddLocation = async (e: React.FormEvent) => {
    e.preventDefault();
    setAdding(true);
    try {
      const res = await fetch("/api/org/locations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: newLocName, address: newLocAddress }),
      });
      if (res.ok) {
        toast.success("Location added");
        setNewLocName("");
        setNewLocAddress("");
        fetchData();
      } else {
        toast.error("Failed to add location");
      }
    } catch {
      toast.error("Failed to add location");
    } finally {
      setAdding(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Add Location */}
      <Card className="glass-card">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-base">
            <Plus className="size-4" />
            Add Location
          </CardTitle>
        </CardHeader>
        <CardContent>
          <form
            onSubmit={handleAddLocation}
            className="flex flex-wrap items-end gap-3"
          >
            <div className="min-w-[200px] flex-1 space-y-1.5">
              <Label className="text-xs">Name</Label>
              <Input
                value={newLocName}
                onChange={(e) => setNewLocName(e.target.value)}
                placeholder="Main Campus"
                required
              />
            </div>
            <div className="min-w-[200px] flex-1 space-y-1.5">
              <Label className="text-xs">Address (optional)</Label>
              <Input
                value={newLocAddress}
                onChange={(e) => setNewLocAddress(e.target.value)}
                placeholder="123 Church St"
              />
            </div>
            <Button type="submit" disabled={adding}>
              {adding ? (
                <Loader2 className="mr-1.5 size-3.5 animate-spin" />
              ) : (
                <Plus className="mr-1.5 size-3.5" />
              )}
              Add
            </Button>
          </form>
        </CardContent>
      </Card>

      {/* Existing Locations */}
      {locations.map((loc) => (
        <Card key={loc.id} className="glass-card">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <MapPin className="size-4" />
              {loc.name}
            </CardTitle>
            {loc.address && (
              <CardDescription>{loc.address}</CardDescription>
            )}
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              <p className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
                <CalendarDays className="size-3.5" />
                Collection Days
              </p>
              {loc.collectionDays.length > 0 ? (
                <div className="space-y-1.5">
                  {loc.collectionDays.map((cd) => (
                    <div
                      key={cd.id}
                      className="flex items-center justify-between rounded-lg border border-border/50 px-3 py-2 text-sm"
                    >
                      <span className="font-medium">{cd.name}</span>
                      <span className="text-muted-foreground">
                        {cd.dayOfWeek != null && DAYS[cd.dayOfWeek]}
                        {cd.timeStart && ` ${cd.timeStart}`}
                        {cd.timeEnd && `–${cd.timeEnd}`}
                      </span>
                    </div>
                  ))}
                </div>
              ) : (
                <p className="text-sm text-muted-foreground">
                  No collection days configured.
                </p>
              )}
            </div>
          </CardContent>
        </Card>
      ))}

      {locations.length === 0 && (
        <div className="glass-card rounded-2xl p-8 text-center text-sm text-muted-foreground">
          No locations yet — add one above.
        </div>
      )}
    </div>
  );
}
