"use client"

import { useState } from "react"
import Modal from "../Modal"

export default function SeamLeakTestSection({ reportId, data }: any) {
  const [tests, setTests] = useState(data || [])
  const [showModal, setShowModal] = useState(false)
  const [formData, setFormData] = useState({ time: new Date().toISOString(), moulds: [{ mouldNumber: "", pass: true }] })

  const addMould = () => {
    setFormData({ ...formData, moulds: [...formData.moulds, { mouldNumber: "", pass: true }] })
  }

  const handleAdd = async () => {
    const updated = [...tests, formData]
    setTests(updated)
    await fetch(`/api/reports/${reportId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ seamLeakTest: updated })
    })
    setShowModal(false)
    setFormData({ time: new Date().toISOString(), moulds: [{ mouldNumber: "", pass: true }] })
  }

  return (
    <div className="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-bold text-gray-800">Seam Leak Test</h2>
        <button onClick={() => setShowModal(true)} className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors">
          + Add Seam Leak Test
        </button>
      </div>

      <div className="space-y-4">
        {tests.map((test: any, i: number) => (
          <div key={i} className="border rounded-lg p-4">
            <p className="font-medium mb-2">Time: {new Date(test.time).toLocaleString()}</p>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
              {test.moulds.map((m: any, j: number) => (
                <div key={j} className="text-sm">
                  Mould {m.mouldNumber}: <span className={m.pass ? "text-green-600" : "text-red-600"}>{m.pass ? "✓ Pass" : "✗ Fail"}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {showModal && (
        <Modal onClose={() => setShowModal(false)}>
          <h3 className="text-lg font-bold mb-4">Add Seam Leak Test</h3>
          <div className="space-y-4">
            <div className="max-h-60 overflow-y-auto space-y-3">
              {formData.moulds.map((mould, i) => (
                <div key={i} className="flex gap-2">
                  <input type="number" placeholder="Mould #" value={mould.mouldNumber} onChange={(e) => {
                    const updated = [...formData.moulds]
                    updated[i].mouldNumber = e.target.value
                    setFormData({...formData, moulds: updated})
                  }} className="flex-1 px-3 py-2 border rounded-lg" />
                  <select value={mould.pass ? "true" : "false"} onChange={(e) => {
                    const updated = [...formData.moulds]
                    updated[i].pass = e.target.value === "true"
                    setFormData({...formData, moulds: updated})
                  }} className="px-3 py-2 border rounded-lg">
                    <option value="true">Pass</option>
                    <option value="false">Fail</option>
                  </select>
                </div>
              ))}
            </div>
            <button onClick={addMould} className="w-full bg-gray-200 text-gray-700 py-2 rounded-lg hover:bg-gray-300">+ Add Mould</button>
            <button onClick={handleAdd} className="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">Save Test</button>
          </div>
        </Modal>
      )}
    </div>
  )
}
