﻿import { useEffect, useState } from 'react';
import api from '../api/client';
import type { InvestorCashout, Investor } from '../types';
import Modal from '../components/Modal';
import { Field, Input, Select } from '../components/FormField';

const today = new Date().toISOString().slice(0, 10);
const emptyForm = { investor_id: '', amount: '', cashout_date: today };

function fmtDate(d: string) {
  return new Date(d + 'T00:00:00').toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' });
}

export default function Cashouts() {
  const [cashouts, setCashouts] = useState<InvestorCashout[]>([]);
  const [investors, setInvestors] = useState<Investor[]>([]);
  const [total, setTotal] = useState(0);
  const [showModal, setShowModal] = useState(false);
  const [editing, setEditing] = useState<InvestorCashout | null>(null);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState(emptyForm);

  const load = () =>
    api.get('/cashouts', { params: { type: 'investor_return' } }).then(r => {
      setCashouts(r.data.cashouts);
      setInvestors(r.data.investors);
      setTotal(r.data.total);
    });

  useEffect(() => { load(); }, []);

  const openCreate = () => {
    setEditing(null);
    setForm(emptyForm);
    setShowModal(true);
  };

  const openEdit = (c: InvestorCashout) => {
    setEditing(c);
    setForm({
      investor_id: c.investor_id ? String(c.investor_id) : '',
      amount: String(c.amount),
      cashout_date: c.cashout_date.slice(0, 10),
    });
    setShowModal(true);
  };

  const save = async () => {
    setSaving(true);
    try {
      const payload = {
        cashout_type: 'investor_return',
        investor_id: Number(form.investor_id),
        amount: Number(form.amount),
        cashout_date: form.cashout_date,
      };
      if (editing) await api.put(`/cashouts/${editing.id}`, payload);
      else await api.post('/cashouts', payload);
      setShowModal(false);
      load();
    } finally { setSaving(false); }
  };

  const del = async (id: number) => {
    if (!confirm('Delete this cashout?')) return;
    await api.delete(`/cashouts/${id}`);
    load();
  };

  const set = (k: string, v: string) => setForm(f => ({ ...f, [k]: v }));

  const selectedInvestor = investors.find(i => String(i.id) === form.investor_id) ?? null;
  const remaining = Math.max(0, Number(selectedInvestor?.total_invested ?? 0) - (Number(form.amount) || 0));

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-gray-900">Investor Cashouts</h1>
          <p className="text-sm text-amber-700 mt-0.5">Total: PKR {Number(total).toLocaleString()}</p>
        </div>
        <button onClick={openCreate} className="px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-sm font-medium transition-colors">
          + Record Cashout
        </button>
      </div>

      <div className="rounded-xl bg-white border border-gray-200 shadow-sm overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-gray-200">
              {['Date', 'Investor', 'Type', 'Amount', 'Actions'].map(h => (
                <th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {cashouts.length === 0 && <tr><td colSpan={5} className="px-4 py-12 text-center text-gray-400">No cashouts yet.</td></tr>}
            {cashouts.map(c => {
              const inv = investors.find(i => i.id === c.investor_id);
              return (
                <tr key={c.id} className="border-b border-gray-100 hover:bg-gray-50">
                  <td className="px-4 py-3 text-gray-700 whitespace-nowrap">{fmtDate(c.cashout_date.slice(0, 10))}</td>
                  <td className="px-4 py-3 font-medium text-gray-900">{c.investor?.name}</td>
                  <td className="px-4 py-3 text-xs text-gray-500">{inv?.type === 'main' ? 'Main' : 'Sub'}</td>
                  <td className="px-4 py-3 font-medium text-amber-700">PKR {Number(c.amount).toLocaleString()}</td>
                  <td className="px-4 py-3">
                    <div className="flex gap-1.5">
                      <button onClick={() => openEdit(c)} className="px-2 py-1 rounded-md bg-gray-100 hover:bg-gray-200 text-gray-700 text-xs">Edit</button>
                      <button onClick={() => del(c.id)} className="px-2 py-1 rounded-md bg-red-50 hover:bg-red-100 text-red-600 text-xs">Del</button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <Modal open={showModal} onClose={() => setShowModal(false)} title={editing ? 'Edit Cashout' : 'Record Cashout'} maxWidth="max-w-sm">
        <div className="space-y-4">
          <Field label="Investor">
            <Select value={form.investor_id} onChange={e => set('investor_id', e.target.value)}>
              <option value="">— Select Investor —</option>
              {investors.map(i => (
                <option key={i.id} value={i.id}>
                  {i.name} ({i.type === 'main' ? 'Main' : 'Sub'})
                </option>
              ))}
            </Select>
          </Field>

          {/* Lock status for sub investors */}
          {selectedInvestor?.type === 'sub' && (
            <div className={`rounded-lg p-3 text-sm border ${selectedInvestor.is_locked ? 'bg-red-500/10 border-red-500/20' : 'bg-emerald-500/10 border-emerald-500/20'}`}>
              {selectedInvestor.is_locked ? (
                <>
                  <p className="text-red-600 font-medium">⚠ Locked until {fmtDate(selectedInvestor.lock_expiry!)}</p>
                  <p className="text-red-600/80 text-xs mt-1">Early withdrawal — profit will be calculated on remaining investment only</p>
                </>
              ) : (
                <p className="text-emerald-700">Lock period expired — free to withdraw</p>
              )}
            </div>
          )}

          <div className="grid grid-cols-2 gap-4">
            <Field label="Amount (PKR)">
              <Input type="number" value={form.amount} onChange={e => set('amount', e.target.value)} step="1" min="1" autoFocus />
            </Field>
            <Field label="Date">
              <Input type="date" value={form.cashout_date} onChange={e => set('cashout_date', e.target.value)} />
            </Field>
          </div>

          {/* Remaining investment preview */}
          {selectedInvestor && form.amount && (
            <div className="flex justify-between text-xs px-1">
              <span className="text-gray-400">Current investment</span>
              <span className="text-gray-700">PKR {Number(selectedInvestor.total_invested ?? 0).toLocaleString()}</span>
            </div>
          )}
          {selectedInvestor && form.amount && (
            <div className="flex justify-between text-xs px-1">
              <span className="text-gray-400">Remaining after cashout</span>
              <span className={remaining < 0 ? 'text-red-600' : 'text-gray-900 font-medium'}>
                PKR {remaining.toLocaleString()}
              </span>
            </div>
          )}

          <div className="flex justify-end gap-2 pt-2">
            <button onClick={() => setShowModal(false)} className="px-4 py-2 rounded-lg bg-gray-100 hover:bg-gray-200 text-gray-900 text-sm">Cancel</button>
            <button onClick={save} disabled={saving || !form.investor_id || !form.amount} className="px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 disabled:opacity-60 text-white text-sm">
              {saving ? 'Saving…' : 'Save'}
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}
