'use client';

import React, { useState } from 'react';
import AppLayout from '@/components/AppLayout';
import { Plus, Search, ShoppingCart, Clock, CheckCircle, XCircle, FileText, Truck } from 'lucide-react';
import Icon from '@/components/ui/AppIcon';


interface PurchaseOrder {
  id: string;
  poNumber: string;
  supplier: string;
  date: string;
  expectedDate: string;
  items: number;
  totalAmount: number;
  status: 'pending' | 'approved' | 'received' | 'cancelled';
  paymentStatus: 'unpaid' | 'partial' | 'paid';
}

const purchaseOrders: PurchaseOrder[] = [
  { id: 'PO001', poNumber: 'PO-2026-089', supplier: 'Unga Group Ltd', date: '2026-08-07', expectedDate: '2026-08-10', items: 5, totalAmount: 48500, status: 'approved', paymentStatus: 'unpaid' },
  { id: 'PO002', poNumber: 'PO-2026-088', supplier: 'Brookside Dairy Ltd', date: '2026-08-06', expectedDate: '2026-08-07', items: 2, totalAmount: 12800, status: 'received', paymentStatus: 'paid' },
  { id: 'PO003', poNumber: 'PO-2026-087', supplier: 'Bidco Africa Ltd', date: '2026-08-05', expectedDate: '2026-08-08', items: 3, totalAmount: 67200, status: 'received', paymentStatus: 'partial' },
  { id: 'PO004', poNumber: 'PO-2026-086', supplier: 'Mumias Sugar Co.', date: '2026-08-04', expectedDate: '2026-08-09', items: 4, totalAmount: 38400, status: 'pending', paymentStatus: 'unpaid' },
  { id: 'PO005', poNumber: 'PO-2026-085', supplier: 'Ketepa Ltd', date: '2026-08-02', expectedDate: '2026-08-06', items: 2, totalAmount: 21000, status: 'cancelled', paymentStatus: 'unpaid' },
  { id: 'PO006', poNumber: 'PO-2026-084', supplier: 'Unilever Kenya Ltd', date: '2026-08-01', expectedDate: '2026-08-05', items: 6, totalAmount: 54600, status: 'received', paymentStatus: 'paid' },
];

const statusConfig = {
  pending: { label: 'Pending', className: 'badge-warning', icon: Clock },
  approved: { label: 'Approved', className: 'badge-info', icon: CheckCircle },
  received: { label: 'Received', className: 'badge-success', icon: Truck },
  cancelled: { label: 'Cancelled', className: 'badge-danger', icon: XCircle },
};

const paymentConfig = {
  unpaid: { label: 'Unpaid', className: 'badge-danger' },
  partial: { label: 'Partial', className: 'badge-warning' },
  paid: { label: 'Paid', className: 'badge-success' },
};

export default function PurchasesPage() {
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);

  const filtered = purchaseOrders.filter((p) =>
    p.poNumber.toLowerCase().includes(search.toLowerCase()) ||
    p.supplier.toLowerCase().includes(search.toLowerCase())
  );

  const totalValue = purchaseOrders.reduce((s, p) => s + p.totalAmount, 0);
  const pending = purchaseOrders.filter((p) => p.status === 'pending').length;
  const received = purchaseOrders.filter((p) => p.status === 'received').length;

  return (
    <AppLayout>
      <div className="p-6 xl:p-8 max-w-screen-2xl mx-auto space-y-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <h1 className="text-xl font-700 text-foreground">Purchases</h1>
            <p className="text-sm text-muted-foreground mt-0.5">Manage purchase orders, GRNs and supplier payments</p>
          </div>
          <button onClick={() => setShowModal(true)} className="btn-primary flex items-center gap-2 px-4 py-2 rounded-md text-sm font-600 text-white">
            <Plus size={16} />
            New Purchase Order
          </button>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[
            { label: 'Total Orders', value: purchaseOrders.length, icon: FileText, color: 'text-primary', bg: 'bg-primary/10' },
            { label: 'Pending', value: pending, icon: Clock, color: 'text-warning', bg: 'bg-warning-bg' },
            { label: 'Received', value: received, icon: Truck, color: 'text-success', bg: 'bg-success-bg' },
            { label: 'Total Value (KES)', value: `${(totalValue / 1000).toFixed(0)}K`, icon: ShoppingCart, color: 'text-info', bg: 'bg-info-bg' },
          ].map((stat) => {
            const Icon = stat.icon;
            return (
              <div key={stat.label} className="card-elevated rounded-xl p-4 flex items-center gap-3">
                <div className={`w-10 h-10 rounded-lg ${stat.bg} flex items-center justify-center flex-shrink-0`}>
                  <Icon size={18} className={stat.color} />
                </div>
                <div>
                  <p className="text-2xl font-700 text-foreground">{stat.value}</p>
                  <p className="text-xs text-muted-foreground">{stat.label}</p>
                </div>
              </div>
            );
          })}
        </div>

        <div className="card-elevated rounded-xl p-4">
          <div className="flex items-center gap-2 bg-muted border border-border rounded-md px-3 h-9 max-w-sm">
            <Search size={14} className="text-muted-foreground" />
            <input type="text" placeholder="Search PO number or supplier…" value={search} onChange={(e) => setSearch(e.target.value)} className="bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none w-full" />
          </div>
        </div>

        <div className="card-elevated rounded-xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-muted/50 border-b border-border">
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">PO Number</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Supplier</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Order Date</th>
                  <th className="text-left px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Expected</th>
                  <th className="text-right px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Items</th>
                  <th className="text-right px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Amount (KES)</th>
                  <th className="text-center px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Status</th>
                  <th className="text-center px-4 py-3 text-xs font-600 text-muted-foreground uppercase tracking-wide">Payment</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filtered.map((po) => {
                  const sc = statusConfig[po.status];
                  const pc = paymentConfig[po.paymentStatus];
                  return (
                    <tr key={po.id} className="hover:bg-muted/30 transition-colors">
                      <td className="px-4 py-3 font-mono text-sm text-primary font-600">{po.poNumber}</td>
                      <td className="px-4 py-3 font-600 text-foreground">{po.supplier}</td>
                      <td className="px-4 py-3 text-xs text-muted-foreground">{po.date}</td>
                      <td className="px-4 py-3 text-xs text-muted-foreground">{po.expectedDate}</td>
                      <td className="px-4 py-3 text-right font-tabular text-foreground">{po.items}</td>
                      <td className="px-4 py-3 text-right font-tabular font-600 text-foreground">{po.totalAmount.toLocaleString()}</td>
                      <td className="px-4 py-3 text-center"><span className={`text-xs px-2 py-0.5 rounded-full font-600 ${sc.className}`}>{sc.label}</span></td>
                      <td className="px-4 py-3 text-center"><span className={`text-xs px-2 py-0.5 rounded-full font-600 ${pc.className}`}>{pc.label}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {showModal && (
          <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
            <div className="bg-card rounded-xl shadow-xl w-full max-w-lg p-6 fade-in">
              <div className="flex items-center justify-between mb-5">
                <h2 className="text-base font-700 text-foreground">New Purchase Order</h2>
                <button onClick={() => setShowModal(false)} className="p-1.5 rounded hover:bg-muted text-muted-foreground">✕</button>
              </div>
              <div className="space-y-4">
                {[{ label: 'Supplier', placeholder: 'Select supplier…' }, { label: 'Expected Delivery Date', placeholder: 'YYYY-MM-DD' }, { label: 'Payment Terms', placeholder: 'Net 30 / COD' }, { label: 'Notes', placeholder: 'Additional notes…' }].map((f) => (
                  <div key={f.label}>
                    <label className="block text-xs font-600 text-foreground mb-1">{f.label}</label>
                    <input placeholder={f.placeholder} className="w-full h-9 px-3 text-sm bg-background border border-border rounded-md outline-none focus:border-primary text-foreground placeholder:text-muted-foreground" />
                  </div>
                ))}
              </div>
              <div className="flex gap-3 mt-6">
                <button onClick={() => setShowModal(false)} className="flex-1 h-9 rounded-md border border-border text-sm text-muted-foreground hover:bg-muted">Cancel</button>
                <button onClick={() => setShowModal(false)} className="flex-1 h-9 rounded-md btn-primary text-sm font-600 text-white">Create PO</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </AppLayout>
  );
}
