import { useRef } from "react"
import { Accordion, AccordionItem, AccordionTrigger, AccordionContent } from "@/Components/ui/accordion"
import { currency } from "@/utils/format"
import WithModal from "@/Components/WithModal"

const ConfirmationModal = ({ id, handleSubmit, processing, data, setData }) => {
  const backButtonRef = useRef()

  // Calculate summary stats
  const stats = data?.budget_categories?.reduce((acc, cat) => {
    cat.budget_details?.forEach(detail => {
      if (detail.is_approved) {
        acc.approved++
        acc.totalApproved += parseFloat(detail._original?.price_total || 0)
      } else if (detail.is_rejected) {
        acc.rejected++
        // Add to rejected list for display
        let catGroup = acc.rejectedList.find(c => c.category_id === cat.category_id)
        if (!catGroup) {
          catGroup = {
            name: cat._category_name,
            category_id: cat.category_id,
            items: []
          }
          acc.rejectedList.push(catGroup)
        }
        catGroup.items.push(detail)
      } else if (detail.is_revision) {
        acc.revision++
        // Add to revision list for display
        let catGroup = acc.revisionList.find(c => c.category_id === cat.category_id)
        if (!catGroup) {
          catGroup = {
            name: cat._category_name,
            category_id: cat.category_id,
            items: []
          }
          acc.revisionList.push(catGroup)
        }
        catGroup.items.push(detail)
      } else {
        acc.unfilled++
      }
    })
    return acc
  }, { approved: 0, rejected: 0, revision: 0, unfilled: 0, totalApproved: 0, rejectedList: [], revisionList: [] })

  return (
    <WithModal type={id} backdrop={true} size="max-w-2xl" boxClassName='modal-box scrollbar-thin overflow-auto'>
      <div className="flex flex-col gap-4">
        <h3 className="font-bold text-lg">Konfirmasi Simpan</h3>

        <div className="grid grid-cols-4 gap-2 text-center my-2">
          <div className="bg-green-50 p-2 rounded border border-green-100">
            <div className="text-2xl font-bold text-green-600">{stats?.approved || 0}</div>
            <div className="text-xs text-green-800">Disetujui</div>
          </div>
          <div className="bg-yellow-50 p-2 rounded border border-yellow-100">
            <div className="text-2xl font-bold text-yellow-600">{stats?.revision || 0}</div>
            <div className="text-xs text-yellow-800">Direvisi</div>
          </div>
          <div className="bg-red-50 p-2 rounded border border-red-100">
            <div className="text-2xl font-bold text-red-600">{stats?.rejected || 0}</div>
            <div className="text-xs text-red-800">Ditolak</div>
          </div>
          <div className="bg-gray-50 p-2 rounded border border-gray-200">
            <div className="text-2xl font-bold text-gray-600">{stats?.unfilled || 0}</div>
            <div className="text-xs text-gray-800">Belum Diisi</div>
          </div>
        </div>

        {stats?.unfilled > 0 && (
          <div className="alert alert-warning text-sm">
            <i className="fas fa-exclamation-triangle"></i>
            <span>Masih ada {stats.unfilled} item yang belum diberikan status persetujuan. Harap lengkapi semua item sebelum menyimpan.</span>
          </div>
        )}

        {(stats?.rejected > 0 || stats?.revision > 0) ? (
          <div className="flex flex-col gap-2 max-h-[60vh] overflow-y-auto pr-1">
            <p className="font-medium text-sm text-gray-600">Detail item yang perlu perhatian:</p>
            <Accordion type="multiple" className="flex flex-col gap-2">
              {[...stats.rejectedList, ...stats.revisionList].map((cat, idx) => (
                <AccordionItem key={idx} value={`grp-${idx}`} className="border rounded px-3 bg-white">
                  <AccordionTrigger className="py-2 hover:no-underline">
                    <span className="text-sm font-semibold">{cat.name} ({cat.items.length} item)</span>
                  </AccordionTrigger>
                  <AccordionContent>
                    <div className="flex flex-col gap-2 py-2">
                      {cat.items.map((item, i) => (
                        <div key={i} className={`p-2 rounded text-xs border ${item.is_rejected ? 'bg-red-50 border-red-100' : 'bg-yellow-50 border-yellow-100'}`}>
                          <div className="flex justify-between font-bold mb-1">
                            <span>{item._original?.name}</span>
                            <span className={`${item.is_rejected ? 'text-red-600 bg-red-100' : 'text-yellow-600 bg-yellow-100'} px-1 rounded`}>
                              {item.is_rejected ? 'Ditolak' : 'Revisi'}
                            </span>
                          </div>
                          <div className="text-gray-500 italic">"{item.status_message || '-'}"</div>
                        </div>
                      ))}
                    </div>
                  </AccordionContent>
                </AccordionItem>
              ))}
            </Accordion>
          </div>
        ) : (
          <>
            {(stats?.unfilled === 0) && (
              <div className="text-center py-4 bg-green-50 rounded border border-green-100">
                <p className="text-sm text-green-800">Semua item telah diperiksa!</p>
                <p className="text-lg font-bold text-green-700 mt-1">Total Disetujui: {currency(stats?.totalApproved || 0)}</p>
              </div>
            )}
          </>
        )}


        <div className="form-control">
          <label className="label">
            <span className="label-text font-semibold">Catatan Tambahan (Opsional)</span>
          </label>
          <textarea
            className="textarea textarea-bordered h-24"
            placeholder="Tambahkan catatan untuk seluruh pengajuan ini..."
            value={data.custom_note}
            onChange={(e) => setData("custom_note", e.target.value)}
          ></textarea>
        </div>

        <p className="text-sm text-gray-500 mt-2">Apakah anda yakin ingin menyimpan perubahan approval ini?</p>

        <div className="modal-action">
          <label ref={backButtonRef} htmlFor={`modal_${id}`} className="btn btn-sm btn-ghost">Batal</label>
          <button
            onClick={() => handleSubmit(() => backButtonRef.current?.click())}
            className="btn btn-primary btn-sm"
            disabled={processing || stats?.unfilled > 0}
          >
            {processing && <span className="loading loading-spinner loading-xs"></span>}
            Ya, Simpan
          </button>
        </div>
      </div>
    </WithModal>
  )
}

export default ConfirmationModal
