"use client";

import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { format, parseISO } from "date-fns";
import { Plus, Pencil, Eye } from "lucide-react";

import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import {
  PageHeader,
  LoadingSpinner,
  StatusBadge,
  MealTypeIcon,
  EmptyState,
} from "@/components/caregiver";
import {
  ORDER_STATUSES,
  getMealTypeLabel,
  type MealType,
  type OrderStatus,
} from "@/lib/constants/meal";

interface MealOrder {
  id: number;
  title: string;
  date: string;
  mealType: MealType;
  status: OrderStatus;
  mealCount: number;
  createdAt: string;
}

export default function OrdersListPage() {
  const router = useRouter();
  const [orders, setOrders] = useState<MealOrder[]>([]);
  const [loading, setLoading] = useState(true);
  const [dateFilter, setDateFilter] = useState(() =>
    format(new Date(), "yyyy-MM-dd"),
  );
  const [statusFilter, setStatusFilter] = useState<string>("all");

  useEffect(() => {
    const fetchOrders = async () => {
      setLoading(true);
      try {
        let url = `/api/meal-orders?sort=-date&limit=100&depth=0`;
        if (dateFilter) {
          url += `&where[date][equals]=${dateFilter}`;
        }
        if (statusFilter !== "all") {
          url += `&where[status][equals]=${statusFilter}`;
        }

        const res = await fetch(url, { credentials: "include" });
        if (res.ok) {
          const data = await res.json();
          setOrders(data.docs || []);
        } else if (res.status === 401) {
          router.push("/login");
        }
      } catch (err) {
        console.error("Error fetching orders:", err);
      } finally {
        setLoading(false);
      }
    };
    fetchOrders();
  }, [router, dateFilter, statusFilter]);

  const handleCreateOrder = async (mealType: MealType) => {
    try {
      const res = await fetch("/api/meal-orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          date: dateFilter,
          mealType,
          status: "draft",
        }),
        credentials: "include",
      });

      if (res.ok) {
        const data = await res.json();
        router.push(`/caregiver/orders/${data.doc.id}`);
      }
    } catch (err) {
      console.error("Error creating order:", err);
    }
  };

  return (
    <div className="min-h-screen bg-muted/50">
      <PageHeader title="Meal Orders" backHref="/caregiver/dashboard" />

      <main className="container py-6">
        <Card className="mb-6">
          <CardHeader>
            <CardTitle>Filter & Create Orders</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid gap-4 sm:grid-cols-3">
              <div className="space-y-2">
                <Label htmlFor="date">Date</Label>
                <Input
                  type="date"
                  id="date"
                  value={dateFilter}
                  onChange={(e) => setDateFilter(e.target.value)}
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="status">Status</Label>
                <Select value={statusFilter} onValueChange={setStatusFilter}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All Statuses</SelectItem>
                    {ORDER_STATUSES.map((status) => (
                      <SelectItem key={status.value} value={status.value}>
                        {status.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Create New Order</Label>
                <div className="flex gap-2">
                  {(["breakfast", "lunch", "dinner"] as const).map((type) => (
                    <Button
                      key={type}
                      variant="outline"
                      size="sm"
                      onClick={() => handleCreateOrder(type)}
                      className="flex-1"
                    >
                      <Plus className="mr-1 h-3 w-3" />
                      {getMealTypeLabel(type)}
                    </Button>
                  ))}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-0">
            {loading ? (
              <LoadingSpinner />
            ) : orders.length === 0 ? (
              <EmptyState
                title="No orders found for the selected date."
                description="Create a new order using the buttons above."
              />
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Meal Type</TableHead>
                    <TableHead>Date</TableHead>
                    <TableHead>Meals</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {orders.map((order) => (
                    <TableRow key={order.id}>
                      <TableCell>
                        <MealTypeIcon type={order.mealType} showLabel />
                      </TableCell>
                      <TableCell>
                        {format(parseISO(order.date), "MMM d, yyyy")}
                      </TableCell>
                      <TableCell>{order.mealCount} residents</TableCell>
                      <TableCell>
                        <StatusBadge status={order.status} />
                      </TableCell>
                      <TableCell className="text-right">
                        <Button variant="outline" size="sm" asChild>
                          <Link href={`/caregiver/orders/${order.id}`}>
                            {order.status === "draft" ? (
                              <>
                                <Pencil className="mr-1 h-3 w-3" />
                                Edit
                              </>
                            ) : (
                              <>
                                <Eye className="mr-1 h-3 w-3" />
                                View
                              </>
                            )}
                          </Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
