'use client'

import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { ArrowLeft, Plus, Loader2, Send, Eye, Pencil, Check, ChefHat } 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 { Badge } from '@/components/ui/badge'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'

interface MealOrder {
  id: number
  title: string
  date: string
  mealType: 'breakfast' | 'lunch' | 'dinner'
  status: 'draft' | 'submitted' | 'preparing' | 'completed'
  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(() => new Date().toISOString().split('T')[0])
  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('/caregiver/login')
        }
      } catch (err) {
        console.error('Error fetching orders:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchOrders()
  }, [router, dateFilter, statusFilter])

  const getMealTypeLabel = (type: string) => {
    switch (type) {
      case 'breakfast':
        return 'Breakfast'
      case 'lunch':
        return 'Lunch'
      case 'dinner':
        return 'Dinner'
      default:
        return type
    }
  }

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'draft':
        return (
          <Badge variant="outline" className="bg-gray-50 text-gray-700 border-gray-200">
            <Pencil className="mr-1 h-3 w-3" />
            Draft
          </Badge>
        )
      case 'submitted':
        return (
          <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
            <Send className="mr-1 h-3 w-3" />
            Submitted
          </Badge>
        )
      case 'preparing':
        return (
          <Badge variant="outline" className="bg-yellow-50 text-yellow-700 border-yellow-200">
            <ChefHat className="mr-1 h-3 w-3" />
            Preparing
          </Badge>
        )
      case 'completed':
        return (
          <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
            <Check className="mr-1 h-3 w-3" />
            Completed
          </Badge>
        )
      default:
        return <Badge variant="outline">{status}</Badge>
    }
  }

  const handleCreateOrder = async (mealType: 'breakfast' | 'lunch' | 'dinner') => {
    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">
      <header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
        <div className="container flex h-16 items-center justify-between">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="sm" asChild>
              <Link href="/caregiver/dashboard">
                <ArrowLeft className="mr-2 h-4 w-4" />
                Back
              </Link>
            </Button>
            <h1 className="text-xl font-semibold">Meal Orders</h1>
          </div>
        </div>
      </header>

      <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>
                    <SelectItem value="draft">Draft</SelectItem>
                    <SelectItem value="submitted">Submitted</SelectItem>
                    <SelectItem value="preparing">Preparing</SelectItem>
                    <SelectItem value="completed">Completed</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Create New Order</Label>
                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleCreateOrder('breakfast')}
                    className="flex-1"
                  >
                    <Plus className="mr-1 h-3 w-3" />
                    Breakfast
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleCreateOrder('lunch')}
                    className="flex-1"
                  >
                    <Plus className="mr-1 h-3 w-3" />
                    Lunch
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => handleCreateOrder('dinner')}
                    className="flex-1"
                  >
                    <Plus className="mr-1 h-3 w-3" />
                    Dinner
                  </Button>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-0">
            {loading ? (
              <div className="flex items-center justify-center p-8">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
              </div>
            ) : orders.length === 0 ? (
              <div className="flex flex-col items-center justify-center p-8 text-center">
                <p className="text-muted-foreground">No orders found for the selected date.</p>
                <p className="text-sm text-muted-foreground mt-2">
                  Create a new order using the buttons above.
                </p>
              </div>
            ) : (
              <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 className="font-medium">
                        {getMealTypeLabel(order.mealType)}
                      </TableCell>
                      <TableCell>{order.date}</TableCell>
                      <TableCell>{order.mealCount} residents</TableCell>
                      <TableCell>{getStatusBadge(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>
  )
}
