"use client";
import { useState, useEffect } from "react";
import { Container } from "@/components/container";
import { Heading } from "@/components/heading";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";

import { NavBar } from "@/components/navbar";
import { Footer } from "@/components/footer";

export default function AdminPage() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [orders, setOrders] = useState<any[]>([]);

  useEffect(() => {
    // Load all orders from localStorage
    const allOrders = [];
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key?.startsWith("order_")) {
        allOrders.push({ id: key.replace("order_", ""), ...JSON.parse(localStorage.getItem(key) || "{}") });
      }
    }
    setOrders(allOrders);
  }, [isLoggedIn]);

  const handleLogin = (e: React.FormEvent) => {
    e.preventDefault();
    if (email === "palacioteni@outlook.com" && password === "12345678") {
      setIsLoggedIn(true);
    } else {
      alert("Credenciales incorrectas");
    }
  };

  const updateOrderStatus = (id: string, status: string) => {
    const order = JSON.parse(localStorage.getItem(`order_${id}`) || "{}");
    order.status = status;
    localStorage.setItem(`order_${id}`, JSON.stringify(order));
    setIsLoggedIn(false); // Trigger reload
    setTimeout(() => setIsLoggedIn(true), 10);
  };

  const updateTracking = (id: string, tracking: string) => {
    const order = JSON.parse(localStorage.getItem(`order_${id}`) || "{}");
    order.trackingNumber = tracking;
    localStorage.setItem(`order_${id}`, JSON.stringify(order));
    alert("Guía actualizada");
  };

  if (!isLoggedIn) {
    return (
      <main>
        <NavBar />
        <Container className="py-32 max-w-md">
        <Card>
          <CardHeader><CardTitle>Admin Login</CardTitle></CardHeader>
          <CardContent>
            <form onSubmit={handleLogin} className="space-y-4">
              <div className="space-y-2">
                <Label>Email</Label>
                <Input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
              </div>
              <div className="space-y-2">
                <Label>Contraseña</Label>
                <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
              </div>
              <Button type="submit" className="w-full">Entrar</Button>
            </form>
          </CardContent>
        </Card>
      </Container>
      <Footer />
    </main>
    );
  }

  return (
    <main>
      <NavBar />
      <Container className="py-32">
      <Heading className="mb-8">Panel de Administración</Heading>
      <Tabs defaultValue="orders">
        <TabsList className="mb-8">
          <TabsTrigger value="orders">Pedidos</TabsTrigger>
          <TabsTrigger value="products">Productos</TabsTrigger>
        </TabsList>
        
        <TabsContent value="orders">
          <div className="grid gap-6">
            {orders.map((order) => (
              <Card key={order.id}>
                <CardContent className="pt-6">
                  <div className="flex flex-col md:flex-row justify-between gap-4">
                    <div>
                      <h3 className="font-bold text-lg">Orden #{order.id}</h3>
                      <p className="text-sm text-neutral-500">{order.name} - {order.email}</p>
                      <p className="text-sm font-medium mt-2">{order.product} - ${order.price} USD</p>
                    </div>
                    <div className="space-y-4">
                      <div className="flex gap-2">
                        <Select defaultValue={order.status} onValueChange={(v) => updateOrderStatus(order.id, v)}>
                          <SelectTrigger className="w-[150px]">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="Pendiente">Pendiente</SelectItem>
                            <SelectItem value="Pagado">Pagado</SelectItem>
                            <SelectItem value="Enviado">Enviado</SelectItem>
                            <SelectItem value="Entregado">Entregado</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="flex gap-2">
                        <Input 
                          placeholder="Número de Guía" 
                          defaultValue={order.trackingNumber} 
                          onBlur={(e) => updateTracking(order.id, e.target.value)}
                        />
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        <TabsContent value="products">
          <Card>
            <CardContent className="pt-6">
              <p className="text-neutral-500">Módulo de edición de productos en desarrollo...</p>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
      </Container>
      <Footer />
    </main>
  );
}
