'use client';

import React, { useState } from 'react';
import { CreditCard, CheckCircle, Clock, Search, Filter, Loader2 } from 'lucide-react';
import { StatusBadge } from '@/components/status-badge';
import { PaymentModal } from '@/components/payment-modal';
import { cn } from '@/lib/utils';

const pendingData = [
  { id: 'INV-2024-001', name: 'Ahmad Fauzi', class: 'X-IPA-1', bill: 'SPP Juli 2024', date: '21 Jun 2026', amount: 'Rp 350.000', bank: 'BSI (Bank Syariah Indonesia)', source: 'Manual' },
  { id: 'INV-2024-002', name: 'Siti Aminah', class: 'XI-IPS-2', bill: 'Uang Gedung (Cicilan 1)', date: '21 Jun 2026', amount: 'Rp 1.500.000', bank: 'BRI', source: 'Otomatis' },
  { id: 'INV-2024-003', name: 'Budi Santoso', class: 'XII-IPA-3', bill: 'Ujian Akhir', date: '20 Jun 2026', amount: 'Rp 450.000', bank: 'BSI (Bank Syariah Indonesia)', source: 'Manual' },
  { id: 'INV-2024-004', name: 'Rina Herawati', class: 'X-IPS-1', bill: 'Seragam', date: '20 Jun 2026', amount: 'Rp 850.000', bank: 'Mandiri', source: 'Manual' },
];

export default function BendaharaDashboard() {
  const [data, setData] = useState(pendingData);
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [isBulkVerifying, setIsBulkVerifying] = useState(false);
  const [isQuickMode, setIsQuickMode] = useState(false);

  const toggleSelectAll = () => {
    if (selectedIds.size === data.length) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(data.map(r => r.id)));
    }
  };

  const toggleRow = (id: string) => {
    const next = new Set(selectedIds);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    setSelectedIds(next);
  };

  const handleBulkApprove = () => {
    setIsBulkVerifying(true);
    setTimeout(() => {
      setIsBulkVerifying(false);
      setData(prev => prev.filter(row => !selectedIds.has(row.id)));
      setSelectedIds(new Set());
    }, 1500);
  };


  return (
    <div className="space-y-6 max-w-7xl mx-auto flex flex-col h-full">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 tracking-tight">Dashboard Bendahara</h1>
          <p className="text-slate-500 text-sm mt-1">Verifikasi pembayaran dan kelola transaksi hari ini.</p>
        </div>
        <div className="flex gap-3">
          <button className="bg-emerald-700 text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-emerald-800 transition-colors shadow-sm flex items-center gap-2">
            <CreditCard className="w-4 h-4" /> Input Pembayaran Offline
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="bg-emerald-700 text-white p-6 rounded-xl shadow-lg border border-emerald-600 relative overflow-hidden">
          <div className="absolute -right-6 -bottom-6 w-32 h-32 bg-emerald-600 rounded-full opacity-50 blur-2xl"></div>
          <p className="text-emerald-100 text-sm font-medium mb-1 relative z-10">Pemasukan Hari Ini</p>
          <p className="text-3xl font-bold relative z-10">Rp 12.500.000</p>
          <p className="text-xs text-emerald-200 mt-2 relative z-10">Dari 45 transaksi terverifikasi</p>
        </div>
        <div className="bg-amber-400 text-amber-900 p-6 rounded-xl shadow-md border border-amber-300 relative overflow-hidden">
          <div className="absolute -right-6 -bottom-6 w-32 h-32 bg-amber-300 rounded-full opacity-50 blur-2xl"></div>
          <p className="text-amber-800 text-sm font-medium mb-1 relative z-10">Menunggu Verifikasi</p>
          <p className="text-3xl font-bold relative z-10">12 Berkas</p>
          <p className="text-xs mt-2 relative z-10 text-amber-800 font-medium">Segera periksa dan verifikasi</p>
        </div>
        <div className="bg-white text-slate-800 p-6 rounded-xl shadow-sm border border-slate-200">
          <p className="text-slate-500 text-sm font-medium mb-1">Total Kas Bulan Ini</p>
          <p className="text-3xl font-bold">Rp 145.2M</p>
          <p className="text-xs text-slate-400 mt-2">Update terakhir: 10 menit lalu</p>
        </div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-slate-200 flex-1 flex flex-col">
        <div className="p-6 border-b border-slate-100 flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="flex items-center gap-4">
            <h3 className="font-bold text-slate-800">Menunggu Verifikasi</h3>
            {selectedIds.size > 1 && (
              <div className="flex items-center gap-2 animate-in fade-in zoom-in-95 duration-200">
                <span className="text-sm text-slate-500 font-medium bg-slate-100 px-2 py-1 rounded-md">{selectedIds.size} dipilih</span>
                <button 
                  onClick={handleBulkApprove}
                  disabled={isBulkVerifying}
                  className="bg-emerald-600 text-white px-3 py-1.5 rounded-lg text-xs font-bold hover:bg-emerald-700 disabled:opacity-70 transition-colors flex items-center gap-2"
                >
                  {isBulkVerifying ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <CheckCircle className="w-3.5 h-3.5" />}
                  {isBulkVerifying ? 'Memproses...' : 'Verifikasi Massal'}
                </button>
              </div>
            )}
          </div>
          <div className="flex gap-2 items-center">
            <div className="flex items-center gap-2 mr-2">
              <span className="text-sm font-medium text-slate-700">Quick Mode</span>
              <button 
                onClick={() => setIsQuickMode(!isQuickMode)}
                className={cn("w-10 h-5 rounded-full transition-colors relative", isQuickMode ? "bg-emerald-500" : "bg-slate-300")}
              >
                <div className={cn("w-4 h-4 bg-white rounded-full absolute top-0.5 transition-transform", isQuickMode ? "translate-x-5.5" : "translate-x-0.5")} />
              </button>
            </div>
            <div className="relative">
              <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
              <input 
                type="text" 
                placeholder="Cari siswa/invoice..." 
                className="pl-9 pr-4 py-2 border border-slate-200 rounded-lg text-sm bg-slate-50 focus:outline-none focus:ring-2 focus:ring-emerald-500/20 focus:border-emerald-500 w-full md:w-64"
              />
            </div>
            <button className="p-2 border border-slate-200 rounded-lg text-slate-500 hover:bg-slate-50">
              <Filter className="w-4 h-4" />
            </button>
          </div>
        </div>
        
        <div className="overflow-x-auto">
          <table className="w-full text-left text-sm whitespace-nowrap">
            <thead className="bg-slate-50 sticky top-0">
              <tr className="text-[10px] uppercase text-slate-400 font-bold">
                <th className="pl-6 py-4 w-10">
                  <input 
                    type="checkbox" 
                    className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 cursor-pointer"
                    checked={selectedIds.size === data.length && data.length > 0}
                    onChange={toggleSelectAll}
                  />
                </th>
                <th className="px-6 py-4">Informasi Siswa</th>
                <th className="px-6 py-4">Jenis Tagihan</th>
                <th className="px-6 py-4">Tgl Transfer</th>
                <th className="px-6 py-4">Nominal</th>
                <th className="px-6 py-4">Sumber Transaksi</th>
                <th className="px-6 py-4">Bank Tujuan</th>
                <th className="px-6 py-4">Status</th>
                <th className="px-6 py-4 text-right">Aksi</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {data.map((row) => (
                <PendingRow 
                  key={row.id} 
                  row={row} 
                  isSelected={selectedIds.has(row.id)}
                  onToggleSelect={() => toggleRow(row.id)}
                  isQuickMode={isQuickMode}
                  onVerify={(id) => {
                    setData(prev => prev.filter(r => r.id !== id));
                    if (selectedIds.has(id)) toggleRow(id);
                  }}
                />
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function PendingRow({ 
  row, 
  isSelected, 
  onToggleSelect,
  isQuickMode,
  onVerify
}: { 
  row: typeof pendingData[0], 
  isSelected: boolean, 
  onToggleSelect: () => void,
  isQuickMode: boolean,
  onVerify: (id: string) => void
}) {
  const [isVerifying, setIsVerifying] = useState(false);
  const [isSuccess, setIsSuccess] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isExpanded, setIsExpanded] = useState(false);

  const handleVerify = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (isQuickMode) {
      setIsVerifying(true);
      setTimeout(() => {
        setIsVerifying(false);
        setIsSuccess(true);
        setTimeout(() => {
          onVerify(row.id);
        }, 500);
      }, 400);
    } else {
      setIsVerifying(true);
      setTimeout(() => {
        setIsVerifying(false);
        onVerify(row.id);
      }, 1500);
    }
  };

  const handleOpenModal = (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsModalOpen(true);
  };

  const handleToggleExpand = (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsExpanded(!isExpanded);
  };

  return (
    <>
      <tr 
        className={cn(
          "transition-all duration-200 cursor-pointer relative",
          isSelected ? "bg-emerald-50 hover:bg-emerald-50 shadow-[inset_4px_0_0_0_#10b981]" : "hover:bg-slate-50",
          "hover:z-10 hover:shadow-[0_0_15px_rgba(16,185,129,0.2)] hover:outline hover:outline-2 hover:outline-emerald-400 hover:[&>td]:py-[17px] [&>td]:transition-all [&>td]:duration-200"
        )} 
        onClick={handleToggleExpand}
      >
        <td className="pl-6 py-4 relative" onClick={(e) => { e.stopPropagation(); onToggleSelect(); }}>
          <input 
            type="checkbox"
            checked={isSelected}
            onChange={() => {}} 
            className="rounded border-slate-300 text-emerald-600 focus:ring-emerald-500 cursor-pointer pointer-events-none"
          />
        </td>
        <td className="px-6 py-4">
          <p className="font-bold text-slate-800">{row.name}</p>
          <p className="text-xs text-slate-500">{row.class} • {row.id}</p>
        </td>
        <td className="px-6 py-4 font-medium text-slate-700">{row.bill}</td>
        <td className="px-6 py-4 text-slate-500">
          <div className="flex items-center gap-1.5"><Clock className="w-3.5 h-3.5" /> {row.date}</div>
        </td>
        <td className="px-6 py-4 font-bold text-emerald-700">{row.amount}</td>
        <td className="px-6 py-4">
          <span className={cn("px-2 py-1 rounded-md text-[10px] font-bold uppercase tracking-wider", row.source === 'Manual' ? "bg-slate-100 text-slate-600" : "bg-blue-50 text-blue-600")}>
            {row.source}
          </span>
        </td>
        <td className="px-6 py-4 text-slate-600 text-xs">{row.bank}</td>
        <td className="px-6 py-4"><StatusBadge status="Pending" variant="dot" /></td>
        <td className="px-6 py-4 text-right">
          <div className="flex items-center justify-end gap-2">
             <button 
               onClick={handleOpenModal}
               className="text-xs font-semibold px-3 py-1.5 rounded bg-slate-100 text-slate-600 hover:bg-slate-200 transition-colors"
             >
              Cek Bukti
            </button>
            <button 
              onClick={handleVerify}
              disabled={isVerifying || isSuccess}
              className={cn(
                "text-xs font-bold px-3 py-1.5 rounded disabled:opacity-70 flex items-center gap-1.5 transition-colors",
                isSuccess ? "bg-emerald-500 text-white" : "bg-emerald-100 text-emerald-700 hover:bg-emerald-200"
              )}
            >
              {isVerifying ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : isSuccess ? <CheckCircle className="w-3.5 h-3.5" /> : null}
              {isVerifying ? 'Verifikasi...' : isSuccess ? 'Sukses' : 'Verifikasi'}
            </button>
          </div>
        </td>
      </tr>
      <tr>
        <td colSpan={9} className="p-0 border-none">
          <div className={cn("grid transition-all duration-300 ease-in-out", isExpanded ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0")}>
            <div className="overflow-hidden">
              <div className="px-6 py-4 bg-slate-50/80 border-b border-slate-100 flex flex-wrap gap-8">
                <div className="space-y-1">
                  <p className="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Catatan Tambahan</p>
                  <p className="text-sm text-slate-700 font-medium">Melalui transfer via mobile banking, sesuai dengan tagihan {row.bill}.</p>
                </div>
                <div className="space-y-1">
                  <p className="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Diverifikasi Oleh</p>
                  <p className="text-sm text-slate-700 border border-slate-200 bg-white px-2 py-0.5 rounded-md inline-block">Sistem / Admin</p>
                </div>
                <div className="space-y-1">
                  <p className="text-[10px] text-slate-500 font-bold uppercase tracking-wider">Referensi Transaksi</p>
                  <p className="text-sm font-mono text-slate-700">TRX-{row.id.split('-')[2]}-{Math.random().toString(36).substring(7).toUpperCase()}</p>
                </div>
              </div>
            </div>
          </div>
        </td>
      </tr>
      <PaymentModal 
        isOpen={isModalOpen} 
        onClose={() => setIsModalOpen(false)} 
        data={row} 
      />
    </>
  );
}
