"use client"

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

export default function HourlyQualityChecksSection({ reportId, data, shiftName }: any) {
  const [checks, setChecks] = useState(data || [])
  const [showModal, setShowModal] = useState(false)
  const [formData, setFormData] = useState({
    time: new Date().toISOString(),
    packInspection: false,
    base: false,
    handle: false,
    body: false,
    neck: false,
    land: false,
    distribution: false,
    phaseCheck: false,
    headTrimmerVisual: false,
    baseWeight: "",
    neckWeight: "",
    headTrimmerMouldClean: false,
    packTensionCheck: false,
    catchTrayInspection: false,
    big: false,
    small: false,
    leakDetector: false,
    vms: false,
    vis: false,
    holdStockAmount: "",
    siloNo: "",
    hdpeIncluded: ""
  })

  const handleAdd = async () => {
    const updated = [...checks, formData]
    setChecks(updated)
    await fetch(`/api/reports/${reportId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ hourlyQualityChecks: updated })
    })
    setShowModal(false)
    // Reset form
    setFormData({
      time: new Date().toISOString(),
      packInspection: false,
      base: false,
      handle: false,
      body: false,
      neck: false,
      land: false,
      distribution: false,
      phaseCheck: false,
      headTrimmerVisual: false,
      baseWeight: "",
      neckWeight: "",
      headTrimmerMouldClean: false,
      packTensionCheck: false,
      catchTrayInspection: false,
      big: false,
      small: false,
      leakDetector: false,
      vms: false,
      vis: false,
      holdStockAmount: "",
      siloNo: "",
      hdpeIncluded: ""
    })
  }

  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">Hourly Quality Checks</h2>
        <button onClick={() => setShowModal(true)} className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors">
          + Add Quality Check
        </button>
      </div>

      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-2 py-2 text-left">Time</th>
              <th className="px-2 py-2 text-left">Base Wt</th>
              <th className="px-2 py-2 text-left">Neck Wt</th>
              <th className="px-2 py-2 text-left">Silo No</th>
              <th className="px-2 py-2 text-left">HDPE %</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {checks.map((c: any, i: number) => (
              <tr key={i}>
                <td className="px-2 py-2">{new Date(c.time).toLocaleTimeString()}</td>
                <td className="px-2 py-2">{c.baseWeight}</td>
                <td className="px-2 py-2">{c.neckWeight}</td>
                <td className="px-2 py-2">{c.siloNo}</td>
                <td className="px-2 py-2">{c.hdpeIncluded}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {showModal && (
        <Modal onClose={() => setShowModal(false)}>
          <div className="max-h-[80vh] overflow-y-auto">
            <h3 className="text-lg font-bold mb-4">Add Hourly Quality Check</h3>
            <div className="space-y-4">
              {/* Time */}
              <div>
                <label className="block text-sm font-medium mb-1">Time</label>
                <input
                  type="time"
                  value={new Date(formData.time).toTimeString().slice(0, 5)}
                  onChange={(e) => {
                    const [hours, minutes] = e.target.value.split(':')
                    const newDate = new Date()
                    newDate.setHours(parseInt(hours), parseInt(minutes))
                    setFormData({...formData, time: newDate.toISOString()})
                  }}
                  className="w-full px-3 py-2 border rounded-lg"
                />
              </div>

              {/* Inspection Checkboxes */}
              <div>
                <label className="block text-sm font-medium mb-2">Inspections (Check if OK)</label>
                <div className="grid grid-cols-2 gap-2">
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.packInspection} onChange={(e) => setFormData({...formData, packInspection: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Pack Inspection</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.base} onChange={(e) => setFormData({...formData, base: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Base</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.handle} onChange={(e) => setFormData({...formData, handle: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Handle</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.body} onChange={(e) => setFormData({...formData, body: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Body</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.neck} onChange={(e) => setFormData({...formData, neck: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Neck</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.land} onChange={(e) => setFormData({...formData, land: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Land</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.distribution} onChange={(e) => setFormData({...formData, distribution: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Distribution</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.phaseCheck} onChange={(e) => setFormData({...formData, phaseCheck: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Phase Check</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.headTrimmerVisual} onChange={(e) => setFormData({...formData, headTrimmerVisual: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Head & Trimmer Visual</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.headTrimmerMouldClean} onChange={(e) => setFormData({...formData, headTrimmerMouldClean: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Head/Trimmer & Mould Clean</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.packTensionCheck} onChange={(e) => setFormData({...formData, packTensionCheck: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Pack Tension Check</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.catchTrayInspection} onChange={(e) => setFormData({...formData, catchTrayInspection: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Catch Tray Inspection</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.big} onChange={(e) => setFormData({...formData, big: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Big</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.small} onChange={(e) => setFormData({...formData, small: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Small</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.leakDetector} onChange={(e) => setFormData({...formData, leakDetector: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">Leak Detector</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.vms} onChange={(e) => setFormData({...formData, vms: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">VMS</span>
                  </label>
                  <label className="flex items-center gap-2">
                    <input type="checkbox" checked={formData.vis} onChange={(e) => setFormData({...formData, vis: e.target.checked})} className="w-4 h-4" />
                    <span className="text-sm">VIS</span>
                  </label>
                </div>
              </div>

              {/* Numeric Fields */}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium mb-1">Base Weight</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.baseWeight}
                    onChange={(e) => setFormData({...formData, baseWeight: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">Neck Weight</label>
                  <input
                    type="number"
                    step="0.1"
                    value={formData.neckWeight}
                    onChange={(e) => setFormData({...formData, neckWeight: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
              </div>

              {/* Text Fields */}
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-sm font-medium mb-1">Hold Stock Amount</label>
                  <input
                    type="text"
                    value={formData.holdStockAmount}
                    onChange={(e) => setFormData({...formData, holdStockAmount: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium mb-1">Silo No.</label>
                  <input
                    type="text"
                    value={formData.siloNo}
                    onChange={(e) => setFormData({...formData, siloNo: e.target.value})}
                    className="w-full px-3 py-2 border rounded-lg"
                  />
                </div>
              </div>

              <div>
                <label className="block text-sm font-medium mb-1">HDPE % Included</label>
                <input
                  type="text"
                  value={formData.hdpeIncluded}
                  onChange={(e) => setFormData({...formData, hdpeIncluded: e.target.value})}
                  className="w-full px-3 py-2 border rounded-lg"
                  placeholder="e.g., 25%"
                />
              </div>

              <button onClick={handleAdd} className="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">
                Add Quality Check
              </button>
            </div>
          </div>
        </Modal>
      )}
    </div>
  )
}
