"use client"

import { useState } from "react"
import Modal from "../Modal"
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from "recharts"

export default function BottleWeightTrackingSection({ reportId, data, shiftName }: any) {
  const [tracking, setTracking] = useState(data || [])
  const [showModal, setShowModal] = useState(false)
  const [formData, setFormData] = useState({ time: new Date().toISOString(), bottle1: "", bottle2: "", bottle3: "", bottle4: "" })

  const handleAdd = async () => {
    const avg = (parseFloat(formData.bottle1) + parseFloat(formData.bottle2) + parseFloat(formData.bottle3) + parseFloat(formData.bottle4)) / 4
    const upperLimit = avg + 0.5
    const lowerLimit = avg - 0.5
    const updated = [...tracking, { ...formData, average: avg, upperLimit, lowerLimit }]
    setTracking(updated)
    await fetch(`/api/reports/${reportId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ bottleWeightTracking: updated })
    })
    setShowModal(false)
    setFormData({ time: new Date().toISOString(), bottle1: "", bottle2: "", bottle3: "", bottle4: "" })
  }

  const chartData = tracking.map((t: any) => ({
    time: new Date(t.time).toLocaleTimeString(),
    average: t.average,
    upperLimit: t.upperLimit,
    lowerLimit: t.lowerLimit,
    target: 34.0
  }))

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

      {tracking.length > 0 && (
        <ResponsiveContainer width="100%" height={300}>
          <LineChart data={chartData}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="time" />
            <YAxis 
              domain={[30, 38]} 
              label={{ value: 'Weight (g)', angle: -90, position: 'insideLeft' }}
              ticks={[30, 31, 32, 33, 34, 35, 36, 37, 38]}
            />
            <Tooltip />
            <Legend />
            <Line type="monotone" dataKey="average" stroke="#3b82f6" name="Average" strokeWidth={2} />
            <Line type="monotone" dataKey="upperLimit" stroke="#ef4444" name="Upper Limit" strokeDasharray="5 5" />
            <Line type="monotone" dataKey="lowerLimit" stroke="#ef4444" name="Lower Limit" strokeDasharray="5 5" />
            <Line type="monotone" dataKey="target" stroke="#10b981" name="Target (34.0g)" strokeDasharray="3 3" strokeWidth={2} />
          </LineChart>
        </ResponsiveContainer>
      )}

      {showModal && (
        <Modal onClose={() => setShowModal(false)}>
          <h3 className="text-lg font-bold mb-4">Add Weight Tracking</h3>
          <div className="space-y-4">
            <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), 0, 0)
                  setFormData({...formData, time: newDate.toISOString()})
                }}
                className="w-full px-3 py-2 border rounded-lg"
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium mb-1">Bottle 1 (g)</label>
                <input type="number" step="0.1" value={formData.bottle1} onChange={(e) => setFormData({...formData, bottle1: e.target.value})} className="w-full px-3 py-2 border rounded-lg" />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Bottle 2 (g)</label>
                <input type="number" step="0.1" value={formData.bottle2} onChange={(e) => setFormData({...formData, bottle2: e.target.value})} className="w-full px-3 py-2 border rounded-lg" />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Bottle 3 (g)</label>
                <input type="number" step="0.1" value={formData.bottle3} onChange={(e) => setFormData({...formData, bottle3: e.target.value})} className="w-full px-3 py-2 border rounded-lg" />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">Bottle 4 (g)</label>
                <input type="number" step="0.1" value={formData.bottle4} onChange={(e) => setFormData({...formData, bottle4: e.target.value})} className="w-full px-3 py-2 border rounded-lg" />
              </div>
            </div>
            <button onClick={handleAdd} className="w-full bg-blue-600 text-white py-2 rounded-lg hover:bg-blue-700">Add</button>
          </div>
        </Modal>
      )}
    </div>
  )
}
