'use client';

import React, { useEffect, useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { Loader, RefreshCw, Settings, Truck, X } from 'lucide-react';

interface Order {
  id: string;
  date: string;
  total: string;
  status: string;
  items: string[];
}

const CustomerAccount: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loyaltyPoints, setLoyaltyPoints] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [settingsOpen, setSettingsOpen] = useState(false);

  useEffect(() => {
    const fetchOrders = async () => {
      try {
        setLoading(true);
        const response = await fetch('/api/swag/customers/123/orders');
        const data = await response.json();
        setOrders(data.orders || []);
        setLoyaltyPoints(data.loyaltyPoints || 250);
        setError(null);
      } catch (err) {
        setError('Failed to fetch order history.');
      } finally {
        setLoading(false);
      }
    };

    fetchOrders();
  }, []);

  const handleReorder = async (orderId: string) => {
    try {
      await fetch('/api/swag/cart', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ orderId }),
      });
      alert('Order added to cart!');
    } catch {
      alert('Failed to reorder. Please try again.');
    }
  };

  const handleTrackOrder = (orderId: string) => {
    alert(`Tracking order: ${orderId}`);
  };

  return (
    <div className="bg-brand-bg min-h-screen text-white p-6">
      <div className="max-w-5xl mx-auto">
        {/* Header */}
        <header className="mb-8">
          <h1 className="text-3xl font-bold">Customer Portal</h1>
          <p className="text-brand">Welcome back! Manage your orders and account settings here.</p>
        </header>

        {/* Loyalty Points */}
        <div className="glass-card p-6 mb-8">
          <h2 className="text-xl font-semibold mb-2">Loyalty Points</h2>
          <p className="text-4xl font-bold text-brand-secondary-light">{loyaltyPoints}</p>
        </div>

        {/* Order History */}
        <div className="glass-card p-6 mb-8">
          <h2 className="text-xl font-semibold mb-4">Order History</h2>
          {loading ? (
            <div className="flex items-center justify-center">
              <Loader className="animate-spin text-brand" size={24} />
            </div>
          ) : error ? (
            <p className="text-red-400">{error}</p>
          ) : orders.length === 0 ? (
            <p className="text-gray-400">No orders found.</p>
          ) : (
            <table className="w-full text-left text-sm">
              <thead>
                <tr className="border-b border-white/10">
                  <th className="py-2">Order ID</th>
                  <th className="py-2">Date</th>
                  <th className="py-2">Total</th>
                  <th className="py-2">Status</th>
                  <th className="py-2">Actions</th>
                </tr>
              </thead>
              <tbody>
                {orders.map((order, index) => (
                  <tr
                    key={order.id}
                    className={`${
                      index % 2 === 0 ? 'bg-white/5' : 'bg-transparent'
                    } hover:bg-white/10 transition`}
                  >
                    <td className="py-2">{order.id}</td>
                    <td className="py-2">{order.date}</td>
                    <td className="py-2">{order.total}</td>
                    <td className="py-2">{order.status}</td>
                    <td className="py-2 flex gap-2">
                      <button
                        onClick={() => handleReorder(order.id)}
                        className="flex items-center gap-1 text-brand hover:text-brand-light transition"
                      >
                        <RefreshCw size={16} />
                        Reorder
                      </button>
                      <button
                        onClick={() => handleTrackOrder(order.id)}
                        className="flex items-center gap-1 text-brand-secondary-light hover:text-brand-secondary-light transition"
                      >
                        <Truck size={16} />
                        Track
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {/* Account Settings */}
        <div className="glass-card p-6">
          <h2 className="text-xl font-semibold mb-4">Account Settings</h2>
          <Dialog.Root open={settingsOpen} onOpenChange={setSettingsOpen}>
            <Dialog.Trigger asChild>
              <button className="flex items-center gap-2 bg-brand text-white px-4 py-2 rounded-lg hover:bg-brand-light transition">
                <Settings size={16} />
                Edit Settings
              </button>
            </Dialog.Trigger>
            <Dialog.Portal>
              <Dialog.Overlay className="fixed inset-0 bg-black/80 z-50" />
              <Dialog.Content className="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 glass-card p-6 max-w-md w-full z-50 rounded-xl">
                <Dialog.Title className="text-lg font-semibold mb-4 text-white">Edit Account Settings</Dialog.Title>
                <form>
                  <div className="mb-4">
                    <label htmlFor="name" className="block text-sm mb-1 text-gray-300">
                      Name
                    </label>
                    <input
                      id="name"
                      type="text"
                      className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-brand"
                    />
                  </div>
                  <div className="mb-4">
                    <label htmlFor="email" className="block text-sm mb-1 text-gray-300">
                      Email
                    </label>
                    <input
                      id="email"
                      type="email"
                      className="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-brand"
                    />
                  </div>
                  <button
                    type="submit"
                    className="bg-brand-secondary-light text-white px-4 py-2 rounded-lg hover:bg-brand-secondary-light transition"
                  >
                    Save Changes
                  </button>
                </form>
                <Dialog.Close asChild>
                  <button className="absolute top-4 right-4 text-gray-400 hover:text-white">
                    <X size={20} />
                  </button>
                </Dialog.Close>
              </Dialog.Content>
            </Dialog.Portal>
          </Dialog.Root>
        </div>
      </div>
    </div>
  );
};

export default CustomerAccount;
