"use client";
import React, { useState } from 'react';
import { Search, Filter, Plus, X, Edit2, Trash2, Copy, Eye, EyeOff } from 'lucide-react';

export default function BrokerManagementApp() {
  const [route, setRoute] = useState('brokers');
  const [modal, setModal] = useState({ show: false, mode: 'add', data: null });
  const [search, setSearch] = useState('');
  const [tab, setTab] = useState('active');
  const [errors, setErrors] = useState({});
  const [hiddenRows, setHiddenRows] = useState([]);
  const [form, setForm] = useState({ name: '', broker: '', apiKey: '', secretKey: '', balance: '' });
  const [brokers, setBrokers] = useState([
    { id: 1, name: 'MarketAxess', apiId: '88234', broker: 'Meta5', date: 'Feb 14, 2025', status: 'active', balance: '$150.25', on: true },
    { id: 2, name: 
      'Tradeweb Markets', apiId: '89245', broker: 'Angel One', date: 'Mar 01, 2025', status: 'inactive', balance: '$175.50', on: true },
    { id: 3, name: 'MarketAxess', apiId: '88234', broker: 'Meta5', date: 'Feb 14, 2025', status: 'active', balance: '$150.25', on: false },
    { id: 4, name: 'Tradeweb Markets', apiId: '89245', broker: 'Zerodha', date: 'Mar 01, 2025', status: 'warning', balance: '$175.50', on: true },
    { id: 5, name: 'MarketAxess', apiId: '88234', broker: 'Dhan', date: 'Feb 14, 2025', status: 'active', balance: '$150.25', on: true },
  ]);

  const brokerList = ['Meta5', 'Angel One', 'Zerodha', 'Dhan', 'Upstox'];
  const routes = ['Dashboard', 'Brokers', 'Scan & Trade', 'Positions', 'AI Strategy Builder'];

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm(prev => ({ ...prev, [name]: value }));
    if (errors[name]) setErrors(prev => ({ ...prev, [name]: '' }));
  };

  const validate = () => {
    const err = {};
    if (!form.name.trim()) err.name = 'Name required';
    if (!form.broker) err.broker = 'Select broker';
    if (!form.apiKey.trim()) err.apiKey = 'API Key required';
    if (!form.secretKey.trim()) err.secretKey = 'Secret Key required';
    if (form.balance && isNaN(parseFloat(form.balance))) err.balance = 'Invalid balance';
    setErrors(err);
    return Object.keys(err).length === 0;
  };

  const openAdd = () => {
    setModal({ show: true, mode: 'add', data: null });
    setForm({ name: '', broker: '', apiKey: '', secretKey: '', balance: '' });
    setErrors({});
  };

  const openEdit = (broker) => {
    setModal({ show: true, mode: 'edit', data: broker });
    setForm({ name: broker.name, broker: broker.broker, apiKey: broker.apiId, secretKey: 'sk-41Z8kLjY...', balance: broker.balance.replace('$', '') });
    setErrors({});
  };

  const deleteBroker = (id) => {
    if (confirm('Delete this broker?')) setBrokers(brokers.filter(b => b.id !== id));
  };

  const submit = () => {
    if (!validate()) return;
    if (modal.mode === 'add') {
      const newBroker = {
        id: Date.now(), name: form.name, apiId: Math.floor(10000 + Math.random() * 90000).toString(),
        broker: form.broker, date: new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
        status: 'active', balance: `$${parseFloat(form.balance || 0).toFixed(2)}`, on: true
      };
      setBrokers([...brokers, newBroker]);
    } else {
      setBrokers(brokers.map(b => b.id === modal.data.id ? { ...b, name: form.name, broker: form.broker, balance: `$${parseFloat(form.balance || 0).toFixed(2)}` } : b));
    }
    setModal({ show: false, mode: 'add', data: null });
  };

  const toggle = (id) => setBrokers(brokers.map(b => b.id === id ? { ...b, on: !b.on } : b));

  const toggleVisibility = (id) => {
    setHiddenRows(prev => prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]);
  };

  const statusIcon = (status) => {
    const colors = { active: 'bg-green-500', inactive: 'bg-red-500', warning: 'bg-yellow-500' };
    return <div className={`w-2 h-2 ${colors[status] || 'bg-green-500'} rounded-full`}></div>;
  };

  const filtered = brokers.filter(b => {
    const matchSearch = b.name.toLowerCase().includes(search.toLowerCase()) || b.broker.toLowerCase().includes(search.toLowerCase());
    const matchTab = tab === 'active' ? b.status === 'active' : tab === 'inactive' ? b.status === 'inactive' : tab === 'expired' ? b.status === 'expired' : true;
    return matchSearch && matchTab && !hiddenRows.includes(b.id);
  });

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white border-b border-gray-200">
        <div className="px-6 py-4 flex items-center justify-between">
          <div className="flex items-center space-x-8">
            <div className="flex items-center space-x-2">
              <div className="w-8 h-8 bg-gray-900 rounded-lg flex items-center justify-center">
                <div className="w-5 h-5 border-2 border-white rounded"></div>
              </div>
              <span className="text-xl font-semibold">Hook nest</span>
            </div>
            <nav className="flex space-x-1">
              {routes.map(r => (
                <button key={r} onClick={() => setRoute(r.toLowerCase().replace(/ & /g, '-').replace(/ /g, '-'))}
                  className={`px-4 py-2 text-sm font-medium ${route === r.toLowerCase().replace(/ & /g, '-').replace(/ /g, '-') ? 'text-teal-600 border-b-2 border-teal-600' : 'text-gray-600'}`}>
                  {r}
                </button>
              ))}
            </nav>
          </div>
          <div className="flex items-center space-x-4">
            <button className="p-2 hover:bg-gray-100 rounded-lg">☾</button>
            <button className="p-2 hover:bg-gray-100 rounded-lg">?</button>
            <button className="p-2 hover:bg-gray-100 rounded-lg">🔔</button>
            <div className="flex items-center space-x-2 border border-gray-200 rounded-lg px-3 py-1.5">
              <span className="text-sm font-medium">NSE</span>
              <span className="text-orange-500">📊</span>
            </div>
            <button className="w-8 h-8 bg-gray-200 rounded-full"></button>
          </div>
        </div>
      </header>

      <main className="p-6">
        {route === 'brokers' ? (
          <div className="bg-white rounded-lg shadow">
            <div className="px-6 py-4 border-b border-gray-200">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center space-x-2 text-sm text-gray-500">
                  <span>👥</span>
                  <span>Brokers / API Management</span>
                </div>
                <div className="flex space-x-4">
                  <button className="text-sm font-medium text-teal-600 border-b-2 border-teal-600 pb-2">API Management</button>
                  <button className="text-sm font-medium text-gray-500 pb-2">Risk Management</button>
                  <button className="text-sm font-medium text-gray-500 pb-2">Hook Hub</button>
                </div>
              </div>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                    <input type="text" placeholder="Search" value={search} onChange={(e) => setSearch(e.target.value)}
                      className="pl-10 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-teal-500" />
                  </div>
                  <button className="flex items-center space-x-2 px-4 py-2 border border-gray-200 rounded-lg text-sm hover:bg-gray-50">
                    <Filter className="w-4 h-4" />
                    <span>Filters</span>
                  </button>
                  <div className="flex space-x-2 bg-gray-100 rounded-lg p-1">
                    {['active', 'inactive', 'expired'].map(t => (
                      <button key={t} onClick={() => setTab(t)}
                        className={`px-4 py-1.5 rounded text-sm font-medium capitalize ${tab === t ? 'bg-white shadow-sm' : 'text-gray-600'}`}>
                        {t}
                      </button>
                    ))}
                  </div>
                </div>
                <div className="flex items-center space-x-3">
                  <button className="flex items-center space-x-2 px-4 py-2 border border-gray-200 rounded-lg text-sm hover:bg-gray-50">
                    <span>Export CSV</span>
                    <span>📥</span>
                  </button>
                  <button onClick={openAdd} className="flex items-center space-x-2 px-4 py-2 bg-teal-500 text-white rounded-lg text-sm hover:bg-teal-600">
                    <span>Add Broker</span>
                    <Plus className="w-4 h-4" />
                  </button>
                </div>
              </div>
            </div>

            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50 border-b border-gray-200">
                  <tr>
                    {['Name', 'API ID', 'Broker', 'Date Added', 'Status', 'Balance', 'Action', 'On/Off'].map(h => (
                      <th key={h} className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {filtered.map(b => (
                    <tr key={b.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 text-sm font-medium text-gray-900">{b.name}</td>
                      <td className="px-6 py-4 text-sm text-gray-500">{b.apiId}</td>
                      <td className="px-6 py-4">
                        <div className="flex items-center space-x-2">
                          <div className="w-5 h-5 bg-gray-200 rounded flex items-center justify-center text-xs">{b.broker[0]}</div>
                          <span className="text-sm text-gray-900">{b.broker}</span>
                        </div>
                      </td>
                      <td className="px-6 py-4 text-sm text-gray-500">{b.date}</td>
                      <td className="px-6 py-4">{statusIcon(b.status)}</td>
                      <td className="px-6 py-4 text-sm font-medium text-green-600">{b.balance}</td>
                      <td className="px-6 py-4">
                        <div className="flex items-center space-x-2">
                          <button onClick={() => toggleVisibility(b.id)} className="p-2 hover:bg-gray-100 rounded">
                            {hiddenRows.includes(b.id) ? <EyeOff className="w-4 h-4 text-gray-400" /> : <Eye className="w-4 h-4 text-gray-400" />}
                          </button>
                          <button onClick={() => openEdit(b)} className="p-2 hover:bg-gray-100 rounded">
                            <Edit2 className="w-4 h-4 text-gray-400" />
                          </button>
                          <button onClick={() => deleteBroker(b.id)} className="p-2 hover:bg-gray-100 rounded">
                            <Trash2 className="w-4 h-4 text-gray-400" />
                          </button>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <button onClick={() => toggle(b.id)}
                          className={`relative inline-flex h-6 w-11 items-center rounded-full ${b.on ? 'bg-teal-500' : 'bg-gray-200'}`}>
                          <span className={`inline-block h-4 w-4 rounded-full bg-white transform transition-transform ${b.on ? 'translate-x-6' : 'translate-x-1'}`} />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        ) : (
          <div className="bg-white rounded-lg shadow p-12 text-center">
            <h2 className="text-2xl font-semibold text-gray-900 mb-2">{routes.find(r => route === r.toLowerCase().replace(/ & /g, '-').replace(/ /g, '-'))}</h2>
            <p className="text-gray-500">This page is under construction</p>
          </div>
        )}
      </main>

      <div className={`fixed inset-0 z-50 transition-opacity duration-300 ${modal.show ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}`}>
        <div className="absolute inset-0 bg-black bg-opacity-50" onClick={() => setModal({ show: false, mode: 'add', data: null })}></div>
        <div className={`absolute right-0 top-0 h-full w-full max-w-md bg-white shadow-xl transform transition-transform duration-300 ${modal.show ? 'translate-x-0' : 'translate-x-full'}`}>
          <div className="h-full flex flex-col">
            <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
              <div>
                <h3 className="text-lg font-semibold text-gray-900">{modal.mode === 'add' ? 'Add Broker' : 'Edit Broker'}</h3>
                <p className="text-sm text-gray-500 mt-1">Choose your preferred exchange to add a broker.</p>
              </div>
              <button onClick={() => setModal({ show: false, mode: 'add', data: null })} className="p-2 hover:bg-gray-100 rounded-lg">
                <X className="w-5 h-5 text-gray-400" />
              </button>
            </div>

            <div className="flex-1 overflow-y-auto px-6 py-6 space-y-6">
              <div className="space-y-4">
                <h4 className="font-semibold text-gray-900">Broker Details</h4>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">Name*</label>
                  <input type="text" name="name" value={form.name} onChange={handleChange} placeholder="Enter a Name"
                    className={`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 ${errors.name ? 'border-red-500' : 'border-gray-200'}`} />
                  {errors.name && <p className="mt-1 text-xs text-red-500">{errors.name}</p>}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">Select Broker</label>
                  <select name="broker" value={form.broker} onChange={handleChange}
                    className={`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 ${errors.broker ? 'border-red-500' : 'border-gray-200'}`}>
                    <option value="">Select Broker</option>
                    {brokerList.map(b => <option key={b} value={b}>{b}</option>)}
                  </select>
                  {errors.broker && <p className="mt-1 text-xs text-red-500">{errors.broker}</p>}
                </div>
              </div>

              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h4 className="font-semibold text-gray-900">API Details</h4>
                  {modal.mode === 'edit' && (
                    <button className="text-sm text-teal-600 hover:text-teal-700 flex items-center space-x-1">
                      <span>Update Key</span>
                      <span>🔄</span>
                    </button>
                  )}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">API Key</label>
                  <div className="relative">
                    <input type="text" name="apiKey" value={form.apiKey} onChange={handleChange} placeholder="api_key_1234567890abcdefABCDE"
                      className={`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 ${errors.apiKey ? 'border-red-500' : 'border-gray-200'}`}
                      readOnly={modal.mode === 'edit'} />
                    <button className="absolute right-3 top-1/2 transform -translate-y-1/2">
                      <Copy className="w-4 h-4 text-gray-400" />
                    </button>
                  </div>
                  {errors.apiKey && <p className="mt-1 text-xs text-red-500">{errors.apiKey}</p>}
                  <p className="mt-1 text-xs text-gray-500">Date {modal.mode === 'add' ? 'Created' : 'Modified'}: {modal.mode === 'add' ? new Date().toLocaleDateString() : '30/12/2025'}</p>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">Secret API Key</label>
                  <input type="password" name="secretKey" value={form.secretKey} onChange={handleChange} placeholder="sk-41Z8kLjY..."
                    className={`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 ${errors.secretKey ? 'border-red-500' : 'border-gray-200'}`} />
                  {errors.secretKey && <p className="mt-1 text-xs text-red-500">{errors.secretKey}</p>}
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1.5">Initial Balance (Optional)</label>
                  <input type="text" name="balance" value={form.balance} onChange={handleChange} placeholder="0.00"
                    className={`w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-teal-500 ${errors.balance ? 'border-red-500' : 'border-gray-200'}`} />
                  {errors.balance && <p className="mt-1 text-xs text-red-500">{errors.balance}</p>}
                </div>
                {modal.mode === 'add' && form.broker && (
                  <a href="#" className="text-sm text-teal-600 hover:text-teal-700">Help me connect to the API</a>
                )}
              </div>
            </div>

            <div className="px-6 py-4 border-t border-gray-200 flex space-x-3">
              <button onClick={() => setModal({ show: false, mode: 'add', data: null })}
                className="flex-1 px-4 py-2.5 border border-gray-200 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-50">
                Cancel
              </button>
              <button onClick={submit} className="flex-1 px-4 py-2.5 bg-teal-500 text-white rounded-lg text-sm font-medium hover:bg-teal-600">
                {modal.mode === 'add' ? 'Add' : 'Save'}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
   