import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Form, useActionData, useLoaderData, useNavigation, Link } from "@remix-run/react";
import { requireAuthLevel } from "~/utils/auth.server";
import DashboardLayout from "~/components/DashboardLayout";
import { useState, useEffect } from "react";
import { manageSheet } from "~/utils/sheet.server";
import { prisma } from "~/utils/db.server";

export const meta: MetaFunction = () => [{ title: "New Report - Phosphat Report" }];

export const loader = async ({ request }: LoaderFunctionArgs) => {
  const user = await requireAuthLevel(request, 1); // All employees can create reports

  // Get dropdown data for form
  const [areas, dredgerLocations, reclamationLocations, foremen, equipment, workers] = await Promise.all([
    prisma.area.findMany({ orderBy: { name: 'asc' } }),
    prisma.dredgerLocation.findMany({ orderBy: { name: 'asc' } }),
    prisma.reclamationLocation.findMany({ orderBy: { name: 'asc' } }),
    prisma.foreman.findMany({ orderBy: { name: 'asc' } }),
    prisma.equipment.findMany({ orderBy: [{ category: 'asc' }, { model: 'asc' }, { number: 'asc' }] }),
    prisma.worker.findMany({ where: { status: 'active' }, orderBy: { name: 'asc' } })
  ]);

  return json({
    user,
    areas,
    dredgerLocations,
    reclamationLocations,
    foremen,
    equipment,
    workers
  });
};

export const action = async ({ request }: ActionFunctionArgs) => {
  const user = await requireAuthLevel(request, 1);

  const formData = await request.formData();

  // Debug logging
  console.log("Form data received:", Object.fromEntries(formData.entries()));

  const createdDate = formData.get("createdDate");
  const shift = formData.get("shift");
  const areaId = formData.get("areaId");
  const dredgerLocationId = formData.get("dredgerLocationId");
  const dredgerLineLength = formData.get("dredgerLineLength");
  const reclamationLocationId = formData.get("reclamationLocationId");
  const shoreConnection = formData.get("shoreConnection");
  const notes = formData.get("notes");

  // Complex JSON fields
  const reclamationHeightBase = formData.get("reclamationHeightBase");
  const reclamationHeightExtra = formData.get("reclamationHeightExtra");
  const pipelineMain = formData.get("pipelineMain");
  const pipelineExt1 = formData.get("pipelineExt1");
  const pipelineReserve = formData.get("pipelineReserve");
  const pipelineExt2 = formData.get("pipelineExt2");
  const statsDozers = formData.get("statsDozers");
  const statsExc = formData.get("statsExc");
  const statsLoaders = formData.get("statsLoaders");
  const statsForeman = formData.get("statsForeman");
  const statsLaborer = formData.get("statsLaborer");
  const workersListData = formData.get("workersList");
  const timeSheetData = formData.get("timeSheetData");
  const stoppagesData = formData.get("stoppagesData");

  // Validation
  // console.log("Validating fields:", { shift, areaId, dredgerLocationId, dredgerLineLength, reclamationLocationId, shoreConnection });

  if (typeof createdDate !== "string" || !createdDate) {
    return json({ errors: { createdDate: "Report date is required" } }, { status: 400 });
  }
  if (typeof shift !== "string" || !["day", "night"].includes(shift)) {
    console.log("Shift validation failed:", shift);
    return json({ errors: { shift: "Valid shift is required" } }, { status: 400 });
  }
  if (typeof areaId !== "string" || !areaId) {
    return json({ errors: { areaId: "Area is required" } }, { status: 400 });
  }
  if (typeof dredgerLocationId !== "string" || !dredgerLocationId) {
    return json({ errors: { dredgerLocationId: "Dredger location is required" } }, { status: 400 });
  }
  if (typeof dredgerLineLength !== "string" || isNaN(parseInt(dredgerLineLength))) {
    return json({ errors: { dredgerLineLength: "Valid dredger line length is required" } }, { status: 400 });
  }
  if (typeof reclamationLocationId !== "string" || !reclamationLocationId) {
    return json({ errors: { reclamationLocationId: "Reclamation location is required" } }, { status: 400 });
  }
  if (typeof shoreConnection !== "string" || isNaN(parseInt(shoreConnection))) {
    return json({ errors: { shoreConnection: "Valid shore connection is required" } }, { status: 400 });
  }

  try {
    // Parse JSON arrays
    let timeSheet = [];
    let stoppages = [];
    let workersList = [];

    if (timeSheetData && typeof timeSheetData === "string") {
      try {
        timeSheet = JSON.parse(timeSheetData);
      } catch (e) {
        timeSheet = [];
      }
    }

    if (stoppagesData && typeof stoppagesData === "string") {
      try {
        stoppages = JSON.parse(stoppagesData);
      } catch (e) {
        stoppages = [];
      }
    }

    if (workersListData && typeof workersListData === "string") {
      try {
        workersList = JSON.parse(workersListData);
      } catch (e) {
        workersList = [];
      }
    }

    // Build automatic notes for pipeline extensions
    const ext1Value = parseInt(pipelineExt1 as string) || 0;
    const ext2Value = parseInt(pipelineExt2 as string) || 0;
    const shiftText = shift === 'day' ? 'Day' : 'Night';

    let automaticNotes = [];

    // Add Extension 1 note if value > 0
    if (ext1Value > 0) {
      automaticNotes.push(`Main Extension ${ext1Value}m ${shiftText}`);
    }

    // Add Extension 2 note if value > 0
    if (ext2Value > 0) {
      automaticNotes.push(`Reserve Extension ${ext2Value}m ${shiftText}`);
    }

    // Combine automatic notes with user notes
    let finalNotes = notes || '';
    if (automaticNotes.length > 0) {
      const automaticNotesText = automaticNotes.join(', ');
      if (finalNotes.trim()) {
        finalNotes = `${automaticNotesText}. ${finalNotes}`;
      } else {
        finalNotes = automaticNotesText;
      }
    }

    // Parse the selected date
    const reportDate = new Date(createdDate);

    const report = await prisma.report.create({
      data: {
        employeeId: user.id,
        createdDate: reportDate,
        shift,
        areaId: parseInt(areaId),
        dredgerLocationId: parseInt(dredgerLocationId),
        dredgerLineLength: parseInt(dredgerLineLength),
        reclamationLocationId: parseInt(reclamationLocationId),
        shoreConnection: parseInt(shoreConnection),
        reclamationHeight: {
          base: parseInt(reclamationHeightBase as string) || 0,
          extra: parseInt(reclamationHeightExtra as string) || 0
        },
        pipelineLength: {
          main: parseInt(pipelineMain as string) || 0,
          ext1: ext1Value,
          reserve: parseInt(pipelineReserve as string) || 0,
          ext2: ext2Value
        },
        stats: {
          Dozers: parseInt(statsDozers as string) || 0,
          Exc: parseInt(statsExc as string) || 0,
          Loaders: parseInt(statsLoaders as string) || 0,
          Foreman: statsForeman as string || "",
          Laborer: workersList.length
        },
        timeSheet,
        stoppages,
        notes: finalNotes || null
      }
    });

    // Create ShiftWorker records for each selected worker
    if (workersList.length > 0) {
      await prisma.shiftWorker.createMany({
        data: workersList.map((workerId: number) => ({
          reportId: report.id,
          workerId: workerId
        }))
      });
    }

    // Manage sheet creation/update
    await manageSheet(
      report.id,
      shift,
      parseInt(areaId),
      parseInt(dredgerLocationId),
      parseInt(reclamationLocationId),
      report.createdDate
    );

    // Redirect to reports page with success message
    return redirect("/reports?success=Report created successfully!");
  } catch (error) {
    return json({ errors: { form: "Failed to create report. Please try again." } }, { status: 400 });
  }
};

export default function NewReport() {
  const { user, areas, dredgerLocations, reclamationLocations, foremen, equipment, workers } = useLoaderData<typeof loader>();
  const actionData = useActionData<typeof action>();
  const navigation = useNavigation();

  // Form state to preserve values across steps
  const [formData, setFormData] = useState({
    createdDate: new Date().toISOString().split('T')[0], // Default to today
    shift: '',
    areaId: '',
    dredgerLocationId: '',
    dredgerLineLength: '',
    reclamationLocationId: '',
    shoreConnection: '',
    reclamationHeightBase: '0',
    reclamationHeightExtra: '0',
    pipelineMain: '0',
    pipelineExt1: '0',
    pipelineReserve: '0',
    pipelineExt2: '0',
    statsDozers: '0',
    statsExc: '0',
    statsLoaders: '0',
    statsForeman: '',
    statsLaborer: '0',
    notes: ''
  });

  const [validationError, setValidationError] = useState<string | null>(null);
  const [selectedWorkers, setSelectedWorkers] = useState<number[]>([]);
  const [workerSearchTerm, setWorkerSearchTerm] = useState('');

  // Dynamic arrays state
  const [timeSheetEntries, setTimeSheetEntries] = useState<Array<{
    id: string,
    machine: string,
    from1: string,
    to1: string,
    from2: string,
    to2: string,
    total: string,
    reason: string
  }>>([]);

  const [stoppageEntries, setStoppageEntries] = useState<Array<{
    id: string,
    from: string,
    to: string,
    total: string,
    reason: string,
    responsible: string,
    note: string
  }>>([]);

  const [currentStep, setCurrentStep] = useState(1);
  const totalSteps = 4;
  const [showZeroEquipmentConfirm, setShowZeroEquipmentConfirm] = useState(false);

  const isSubmitting = navigation.state === "submitting";

  // Function to update form data
  const updateFormData = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // Handle form submission - only allow on final step
  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    // console.log("Form submit triggered, current step:", currentStep);

    if (currentStep !== totalSteps) {
      console.log("Preventing form submission - not on final step");
      event.preventDefault();
      event.stopPropagation();
      return false;
    }

    // Validate reclamation stoppages have notes
    const invalidStoppages = stoppageEntries.filter(entry =>
      entry.responsible === 'reclamation' && !entry.note.trim()
    );

    if (invalidStoppages.length > 0) {
      alert('Please add notes for all reclamation stoppages before submitting.');
      event.preventDefault();
      event.stopPropagation();
      return false;
    }

    // console.log("Allowing form submission");
    // console.log("Form being submitted with data:", formData);
    // console.log("Time sheet entries:", timeSheetEntries);
    // console.log("Stoppage entries:", stoppageEntries);
  };

  // Helper functions for time calculations
  const calculateTimeDifference = (from1: string, to1: string, from2: string, to2: string) => {
    if (!from1 || !to1) return "00:00";

    const parseTime = (timeStr: string) => {
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    };

    const formatTime = (minutes: number) => {
      const hours = Math.floor(minutes / 60);
      const mins = minutes % 60;
      return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`;
    };

    let totalMinutes = 0;

    if (from1 && to1) {
      const start1 = parseTime(from1);
      let end1 = parseTime(to1);

      if (end1 < start1) {
        end1 += 24 * 60;
      }

      totalMinutes += end1 - start1;
    }

    if (from2 && to2) {
      const start2 = parseTime(from2);
      let end2 = parseTime(to2);


      if (end2 < start2) {
        end2 += 24 * 60;
      }
      totalMinutes += end2 - start2;
    }

    return formatTime(Math.max(0, totalMinutes));
    //return formatTime(Math.max(totalMinutes * -1, totalMinutes));
  };

  const calculateStoppageTime = (from: string, to: string) => {
    if (!from || !to) return "00:00";

    const parseTime = (timeStr: string) => {
      const [hours, minutes] = timeStr.split(':').map(Number);
      return hours * 60 + minutes;
    };

    const formatTime = (minutes: number) => {
      const hours = Math.floor(minutes / 60);
      const mins = minutes % 60;
      return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}`;
    };

    const startMinutes = parseTime(from);
    let endMinutes = parseTime(to);
    if (endMinutes < startMinutes)
      endMinutes += 24 * 60;
    const totalMinutes = Math.max(0, endMinutes - startMinutes);

    return formatTime(totalMinutes);
  };

  // Time Sheet management
  const addTimeSheetEntry = () => {
    const newEntry = {
      id: Date.now().toString(),
      machine: '',
      from1: '',
      to1: '',
      from2: '',
      to2: '',
      total: '00:00',
      reason: ''
    };
    setTimeSheetEntries([...timeSheetEntries, newEntry]);
  };

  const removeTimeSheetEntry = (id: string) => {
    setTimeSheetEntries(timeSheetEntries.filter(entry => entry.id !== id));
  };

  const updateTimeSheetEntry = (id: string, field: string, value: string) => {
    setTimeSheetEntries(timeSheetEntries.map(entry => {
      if (entry.id === id) {
        const updatedEntry = { ...entry, [field]: value };
        if (['from1', 'to1', 'from2', 'to2'].includes(field)) {
          updatedEntry.total = calculateTimeDifference(
            updatedEntry.from1,
            updatedEntry.to1,
            updatedEntry.from2,
            updatedEntry.to2
          );
        }
        return updatedEntry;
      }
      return entry;
    }));
  };

  // Fetch last report data when location combination is complete (in step 2)
  useEffect(() => {
    const fetchLastReportData = async () => {
      if (currentStep === 2 && formData.areaId && formData.dredgerLocationId && formData.reclamationLocationId) {
        try {
          const response = await fetch(
            `/api/last-report-data?areaId=${formData.areaId}&dredgerLocationId=${formData.dredgerLocationId}&reclamationLocationId=${formData.reclamationLocationId}`
          );
          const data = await response.json();

          if (data.data) {
            // Only update fields that are still at their default values
            setFormData(prev => {
              const updates: any = {};
              
              // Update dredger line length if still empty or default
              if (!prev.dredgerLineLength || prev.dredgerLineLength === '') {
                updates.dredgerLineLength = data.data.dredgerLineLength.toString();
              }
              
              // Update shore connection if still empty or default
              if (!prev.shoreConnection || prev.shoreConnection === '') {
                updates.shoreConnection = data.data.shoreConnection.toString();
              }
              
              // Update reclamation height base if still at default
              if (prev.reclamationHeightBase === '0') {
                updates.reclamationHeightBase = data.data.reclamationHeightBase.toString();
              }
              
              // Update pipeline main if still at default
              if (prev.pipelineMain === '0') {
                updates.pipelineMain = data.data.pipelineMain.toString();
              }
              
              // Update pipeline reserve if still at default
              if (prev.pipelineReserve === '0') {
                updates.pipelineReserve = data.data.pipelineReserve.toString();
              }

              return Object.keys(updates).length > 0 ? { ...prev, ...updates } : prev;
            });
          }
        } catch (error) {
          console.error('Error fetching last report data:', error);
        }
      }
    };

    fetchLastReportData();
  }, [currentStep, formData.areaId, formData.dredgerLocationId, formData.reclamationLocationId]);

  // Auto-calculate equipment counts based on time sheet entries
  useEffect(() => {
    const counts = { dozers: 0, excavators: 0, loaders: 0 };

    timeSheetEntries.forEach(entry => {
      if (entry.machine) {
        const equipmentItem = equipment.find(item =>
          `${item.model} (${item.number})` === entry.machine
        );
        if (equipmentItem) {
          const category = equipmentItem.category.toLowerCase();
          if (category.includes('dozer')) {
            counts.dozers++;
          } else if (category.includes('excavator')) {
            counts.excavators++;
          } else if (category.includes('loader')) {
            counts.loaders++;
          }
        }
      }
    });

    // Update form data with calculated counts
    setFormData(prev => ({
      ...prev,
      statsDozers: counts.dozers.toString(),
      statsExc: counts.excavators.toString(),
      statsLoaders: counts.loaders.toString()
    }));
  }, [timeSheetEntries, equipment]);

  // Stoppage management
  const addStoppageEntry = () => {
    const newEntry = {
      id: Date.now().toString(),
      from: '',
      to: '',
      total: '00:00',
      reason: '', // Will be set to 'none' for reclamation by default
      responsible: 'reclamation', // Default to reclamation
      note: ''
    };
    setStoppageEntries([...stoppageEntries, newEntry]);
  };

  const removeStoppageEntry = (id: string) => {
    setStoppageEntries(stoppageEntries.filter(entry => entry.id !== id));
  };

  const updateStoppageEntry = (id: string, field: string, value: string) => {
    setStoppageEntries(stoppageEntries.map(entry => {
      if (entry.id === id) {
        const updatedEntry = { ...entry, [field]: value };
        if (['from', 'to'].includes(field)) {
          updatedEntry.total = calculateStoppageTime(updatedEntry.from, updatedEntry.to);
        }
        // Handle responsible party change
        if (field === 'responsible') {
          if (value === 'reclamation') {
            updatedEntry.reason = ''; // Set to empty for reclamation (will show as "None")
          }
          // If changing to dredger, keep current reason or allow user to select
        }
        return updatedEntry;
      }
      return entry;
    }));
  };

  const nextStep = async (event?: React.MouseEvent<HTMLButtonElement>) => {
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }

    // Check for duplicate report on step 1
    if (currentStep === 1) {
      try {
        const response = await fetch('/api/check-duplicate-report', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            createdDate: formData.createdDate,
            shift: formData.shift,
            areaId: formData.areaId,
            dredgerLocationId: formData.dredgerLocationId,
            reclamationLocationId: formData.reclamationLocationId
          })
        });

        const data = await response.json();
        
        if (data.exists) {
          setValidationError(`A report already exists for ${formData.shift} shift in this area, dredger location, and reclamation location on ${new Date(formData.createdDate).toLocaleDateString()}`);
          return;
        }
        
        setValidationError(null);
      } catch (error) {
        console.error('Error checking for duplicate:', error);
        setValidationError('Failed to validate report. Please try again.');
        return;
      }
    }

    // Check if we're on step 3 (Equipment & Time Sheet) and have zero equipment
    if (currentStep === 3) {
      const totalEquipment = parseInt(formData.statsDozers) + parseInt(formData.statsExc) + parseInt(formData.statsLoaders);
      if (totalEquipment === 0) {
        setShowZeroEquipmentConfirm(true);
        return;
      }
    }

    // console.log("Next step clicked, current step:", currentStep);
    if (currentStep < totalSteps) {
      setCurrentStep(currentStep + 1);
      // console.log("Moving to step:", currentStep + 1);
    }
  };

  const confirmZeroEquipmentAndProceed = () => {
    setShowZeroEquipmentConfirm(false);
    if (currentStep < totalSteps) {
      setCurrentStep(currentStep + 1);
    }
  };

  const cancelZeroEquipmentConfirm = () => {
    setShowZeroEquipmentConfirm(false);
  };

  const prevStep = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const getStepTitle = (step: number) => {
    switch (step) {
      case 1: return "Basic Information";
      case 2: return "Location & Pipeline Details";
      case 3: return "Equipment & Time Sheet";
      case 4: return "Stoppages & Notes";
      default: return "";
    }
  };

  // Validation functions for each step
  const isStep1Valid = () => {
    return formData.createdDate &&
      formData.shift &&
      formData.areaId &&
      formData.dredgerLocationId &&
      formData.reclamationLocationId;
  };

  const isStep2Valid = () => {
    return formData.dredgerLineLength &&
      !isNaN(parseInt(formData.dredgerLineLength)) &&
      formData.shoreConnection &&
      !isNaN(parseInt(formData.shoreConnection));
  };

  const isStep3Valid = () => {
    // Step 3 has no required fields - equipment and time sheet are optional
    return true;
  };

  const isCurrentStepValid = () => {
    switch (currentStep) {
      case 1: return isStep1Valid();
      case 2: return isStep2Valid();
      case 3: return isStep3Valid();
      case 4: return true; // Step 4 has no required fields
      default: return false;
    }
  };

  // Worker selection functions
  const toggleWorker = (workerId: number) => {
    setSelectedWorkers(prev =>
      prev.includes(workerId)
        ? prev.filter(id => id !== workerId)
        : [...prev, workerId]
    );
  };

  const filteredWorkers = workers.filter(worker =>
    worker.name.toLowerCase().includes(workerSearchTerm.toLowerCase()) &&
    !selectedWorkers.includes(worker.id)
  );

  return (
    <DashboardLayout user={user}>
      <div className="max-w-full mx-auto">
        {/* Header */}
        <div className="mb-6 sm:mb-8">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-4 sm:space-y-0">
            <div>
              <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">Create New Shifts</h1>
              <p className="mt-2 text-sm sm:text-base text-gray-600">Fill out the operational shift details step by step</p>
            </div>
            <Link
              to="/reports"
              className="inline-flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
            >
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              Back to Shifts
            </Link>
          </div>
        </div>

        {/* Progress Steps */}
        <div className="mb-6 sm:mb-8">
          <div className="flex items-center justify-between px-2 sm:px-0">
            {[1, 2, 3, 4].map((step) => (
              <div key={step} className="flex items-center">
                <div className={`flex items-center justify-center w-8 h-8 sm:w-10 sm:h-10 rounded-full border-2 ${step <= currentStep
                  ? 'bg-indigo-600 border-indigo-600 text-white'
                  : 'border-gray-300 text-gray-500'
                  }`}>
                  {step < currentStep ? (
                    <svg className="w-4 h-4 sm:w-6 sm:h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                  ) : (
                    <span className="text-xs sm:text-sm font-medium">{step}</span>
                  )}
                </div>
                {step < totalSteps && (
                  <div className={`flex-1 h-1 mx-2 sm:mx-4 ${step < currentStep ? 'bg-indigo-600' : 'bg-gray-300'
                    }`} />
                )}
              </div>
            ))}
          </div>
          <div className="mt-4 text-center">
            <h2 className="text-lg sm:text-xl font-semibold text-gray-900">{getStepTitle(currentStep)}</h2>
            <p className="text-xs sm:text-sm text-gray-500">Step {currentStep} of {totalSteps}</p>
          </div>
        </div>

        {/* Form */}
        <Form method="post" onSubmit={handleSubmit} className="bg-white shadow-lg rounded-lg overflow-hidden">
          <div className="p-4 sm:p-6">
            {/* Step 1: Basic Information */}
            {currentStep === 1 && (
              <div className="space-y-4 sm:space-y-6">
                {validationError && (
                  <div className="p-4 bg-red-50 border border-red-200 rounded-md">
                    <div className="flex">
                      <svg className="h-5 w-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      <div className="ml-3">
                        <p className="text-sm text-red-800">{validationError}</p>
                      </div>
                    </div>
                  </div>
                )}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                  <div>
                    <label htmlFor="createdDate" className="block text-sm font-medium text-gray-700 mb-2">
                      Report Date <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="date"
                      id="createdDate"
                      name="createdDate"
                      required
                      value={formData.createdDate}
                      onChange={(e) => {
                        updateFormData('createdDate', e.target.value);
                        setValidationError(null);
                      }}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    />
                  </div>
                  <div>
                    <label htmlFor="shift" className="block text-sm font-medium text-gray-700 mb-2">
                      Shift <span className="text-red-500">*</span>
                    </label>
                    <select
                      id="shift"
                      name="shift"
                      required
                      value={formData.shift}
                      onChange={(e) => updateFormData('shift', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    >
                      <option value="">Select shift</option>
                      <option value="day">Day Shift</option>
                      <option value="night">Night Shift</option>
                    </select>
                    {actionData?.errors?.shift && (
                      <p className="mt-1 text-sm text-red-600">{actionData.errors.shift}</p>
                    )}
                  </div>

                  <div>
                    <label htmlFor="areaId" className="block text-sm font-medium text-gray-700 mb-2">
                      Area <span className="text-red-500">*</span>
                    </label>
                    <select
                      id="areaId"
                      name="areaId"
                      required
                      value={formData.areaId}
                      onChange={(e) => updateFormData('areaId', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    >
                      <option value="">Select area</option>
                      {areas.map((area) => (
                        <option key={area.id} value={area.id}>
                          {area.name}
                        </option>
                      ))}
                    </select>
                    {actionData?.errors?.areaId && (
                      <p className="mt-1 text-sm text-red-600">{actionData.errors.areaId}</p>
                    )}
                  </div>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                  <div>
                    <label htmlFor="dredgerLocationId" className="block text-sm font-medium text-gray-700 mb-2">
                      Dredger Location <span className="text-red-500">*</span>
                    </label>
                    <select
                      id="dredgerLocationId"
                      name="dredgerLocationId"
                      required
                      value={formData.dredgerLocationId}
                      onChange={(e) => updateFormData('dredgerLocationId', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    >
                      <option value="">Select dredger location</option>
                      {dredgerLocations.map((location) => (
                        <option key={location.id} value={location.id}>
                          {location.name} ({location.class.toUpperCase()})
                        </option>
                      ))}
                    </select>
                    {actionData?.errors?.dredgerLocationId && (
                      <p className="mt-1 text-sm text-red-600">{actionData.errors.dredgerLocationId}</p>
                    )}
                  </div>

                  <div>
                    <label htmlFor="reclamationLocationId" className="block text-sm font-medium text-gray-700 mb-2">
                      Reclamation Location <span className="text-red-500">*</span>
                    </label>
                    <select
                      id="reclamationLocationId"
                      name="reclamationLocationId"
                      required
                      value={formData.reclamationLocationId}
                      onChange={(e) => updateFormData('reclamationLocationId', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                    >
                      <option value="">Select reclamation location</option>
                      {reclamationLocations.map((location) => (
                        <option key={location.id} value={location.id}>{location.name}</option>
                      ))}
                    </select>
                    {actionData?.errors?.reclamationLocationId && (
                      <p className="mt-1 text-sm text-red-600">{actionData.errors.reclamationLocationId}</p>
                    )}
                  </div>
                </div>
              </div>
            )}
            {/* Step 2: Location & Pipeline Details */}
            {currentStep === 2 && (
              <div className="space-y-4 sm:space-y-6">
                {/* Info message about carry-forward */}
                <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                  <div className="flex">
                    <svg className="h-5 w-5 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <div className="ml-3">
                      <p className="text-sm text-blue-800">
                        Values below are automatically filled from the last report for this location combination. You can modify them as needed.
                      </p>
                    </div>
                  </div>
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                  <div>
                    <label htmlFor="dredgerLineLength" className="block text-sm font-medium text-gray-700 mb-2">
                      Dredger Line Length (m) <span className="text-red-500">*</span>
                    </label>
                    <input
                      type="number"
                      id="dredgerLineLength"
                      name="dredgerLineLength"
                      required
                      min="0"
                      value={formData.dredgerLineLength}
                      onChange={(e) => updateFormData('dredgerLineLength', e.target.value)}
                      className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                      placeholder="Enter length in meters"
                    />
                    {actionData?.errors?.dredgerLineLength && (
                      <p className="mt-1 text-sm text-red-600">{actionData.errors.dredgerLineLength}</p>
                    )}
                  </div>
                  <div>
                    <label htmlFor="shoreConnection" className="block text-sm font-medium text-gray-700 mb-2">Shore Connection <span className="text-red-500">*</span></label>
                    <input type="number" id="shoreConnection" name="shoreConnection" required min="0" value={formData.shoreConnection} onChange={(e) => updateFormData('shoreConnection', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="Enter connection length" />
                    {actionData?.errors?.shoreConnection && (
                      <p className="mt-1 text-sm text-red-600">{actionData.errors.shoreConnection}</p>
                    )}
                  </div>
                </div>
                <div>
                  <h3 className="text-base sm:text-lg font-medium text-gray-900 mb-4">Reclamation Height</h3>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
                    <div><label htmlFor="reclamationHeightBase" className="block text-sm font-medium text-gray-700 mb-2">Base Height (m)</label><input type="number" id="reclamationHeightBase" name="reclamationHeightBase" min="0" value={formData.reclamationHeightBase} onChange={(e) => updateFormData('reclamationHeightBase', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                    <div><label htmlFor="reclamationHeightExtra" className="block text-sm font-medium text-gray-700 mb-2">Extra Height (m)</label><input type="number" id="reclamationHeightExtra" name="reclamationHeightExtra" min="0" value={formData.reclamationHeightExtra} onChange={(e) => updateFormData('reclamationHeightExtra', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                  </div>
                </div>
                <div>
                  <h3 className="text-base sm:text-lg font-medium text-gray-900 mb-4">Pipeline Length</h3>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4">
                    <div><label htmlFor="pipelineMain" className="block text-sm font-medium text-gray-700 mb-2">Main</label><input type="number" id="pipelineMain" name="pipelineMain" min="0" value={formData.pipelineMain} onChange={(e) => updateFormData('pipelineMain', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                    <div><label htmlFor="pipelineExt1" className="block text-sm font-medium text-gray-700 mb-2">Extension 1</label><input type="number" id="pipelineExt1" name="pipelineExt1" min="0" value={formData.pipelineExt1} onChange={(e) => updateFormData('pipelineExt1', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                    <div><label htmlFor="pipelineReserve" className="block text-sm font-medium text-gray-700 mb-2">Reserve</label><input type="number" id="pipelineReserve" name="pipelineReserve" min="0" value={formData.pipelineReserve} onChange={(e) => updateFormData('pipelineReserve', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                    <div><label htmlFor="pipelineExt2" className="block text-sm font-medium text-gray-700 mb-2">Extension 2</label><input type="number" id="pipelineExt2" name="pipelineExt2" min="0" value={formData.pipelineExt2} onChange={(e) => updateFormData('pipelineExt2', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                  </div>
                </div>
              </div>
            )}
            {/* Step 3: Equipment & Time Sheet */}
            {currentStep === 3 && (
              <div className="space-y-4 sm:space-y-6">
                <div>
                  <h3 className="text-base sm:text-lg font-medium text-gray-900 mb-4">Equipment Statistics</h3>
                  <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 sm:gap-4">
                    <div><label htmlFor="statsDozers" className="block text-sm font-medium text-gray-700 mb-2">Dozers <span className="text-xs text-gray-500">(Auto-calculated)</span></label><input type="number" id="statsDozers" name="statsDozers" min="0" value={formData.statsDozers} readOnly className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100 text-gray-700 cursor-not-allowed" title="Auto-calculated based on time sheet entries" /></div>
                    <div><label htmlFor="statsExc" className="block text-sm font-medium text-gray-700 mb-2">Excavators <span className="text-xs text-gray-500">(Auto-calculated)</span></label><input type="number" id="statsExc" name="statsExc" min="0" value={formData.statsExc} readOnly className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100 text-gray-700 cursor-not-allowed" title="Auto-calculated based on time sheet entries" /></div>
                    <div><label htmlFor="statsLoaders" className="block text-sm font-medium text-gray-700 mb-2">Loaders <span className="text-xs text-gray-500">(Auto-calculated)</span></label><input type="number" id="statsLoaders" name="statsLoaders" min="0" value={formData.statsLoaders} readOnly className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100 text-gray-700 cursor-not-allowed" title="Auto-calculated based on time sheet entries" /></div>
                    <div><label htmlFor="statsForeman" className="block text-sm font-medium text-gray-700 mb-2">Foreman</label><select id="statsForeman" name="statsForeman" value={formData.statsForeman} onChange={(e) => updateFormData('statsForeman', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"><option value="">Select foreman</option>{foremen.map((foreman) => (<option key={foreman.id} value={foreman.name}>{foreman.name}</option>))}</select></div>
                    <div><label htmlFor="statsLaborer" className="block text-sm font-medium text-gray-700 mb-2">Laborers <span className="text-xs text-gray-500">({selectedWorkers.length} selected)</span></label><input type="number" id="statsLaborer" name="statsLaborer" min="0" value={selectedWorkers.length} readOnly className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100 text-gray-700 cursor-not-allowed" title="Auto-calculated based on selected workers" /></div>
                  </div>
                </div>
                <div>
                  <h3 className="text-base sm:text-lg font-medium text-gray-900 mb-4">Select Workers</h3>
                  <div className="space-y-3">
                    <div className="relative">
                      <input
                        type="text"
                        placeholder="Search workers..."
                        value={workerSearchTerm}
                        onChange={(e) => setWorkerSearchTerm(e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                      />
                      {workerSearchTerm && filteredWorkers.length > 0 && (
                        <div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto">
                          {filteredWorkers.map((worker) => (
                            <button
                              key={worker.id}
                              type="button"
                              onClick={() => {
                                toggleWorker(worker.id);
                                setWorkerSearchTerm('');
                              }}
                              className="w-full text-left px-4 py-2 hover:bg-gray-100 focus:outline-none focus:bg-gray-100"
                            >
                              {worker.name}
                            </button>
                          ))}
                        </div>
                      )}
                    </div>
                    {selectedWorkers.length > 0 && (
                      <div className="flex flex-wrap gap-2">
                        {selectedWorkers.map((workerId) => {
                          const worker = workers.find(w => w.id === workerId);
                          return worker ? (
                            <span
                              key={workerId}
                              className="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-indigo-100 text-indigo-800"
                            >
                              {worker.name}
                              <button
                                type="button"
                                onClick={() => toggleWorker(workerId)}
                                className="ml-2 inline-flex items-center justify-center w-4 h-4 text-indigo-600 hover:text-indigo-800"
                              >
                                <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                                  <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                                </svg>
                              </button>
                            </span>
                          ) : null;
                        })}
                      </div>
                    )}
                  </div>
                </div>
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="text-lg font-medium text-gray-900">Time Sheet</h3>
                    <button type="button" onClick={addTimeSheetEntry} className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                      <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" /></svg>Add Entry
                    </button>
                  </div>
                  {timeSheetEntries.length > 0 ? (
                    <div className="space-y-4">
                      {timeSheetEntries.map((entry) => (
                        <div key={entry.id} className="bg-gray-50 p-4 rounded-lg">
                          <div className="grid grid-cols-1 md:grid-cols-7 gap-4">
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">Equipment</label><select value={entry.machine} onChange={(e) => updateTimeSheetEntry(entry.id, 'machine', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"><option value="">Select Equipment</option>{equipment.filter((item) => {
                              const machineValue = `${item.model} (${item.number})`;
                              // Show if not selected by any other entry, or if it's the current entry's selection
                              return !timeSheetEntries.some(e => e.id !== entry.id && e.machine === machineValue);
                            }).map((item) => (<option key={item.id} value={`${item.model} (${item.number})`}>{item.category} - {item.model} ({item.number})</option>))}</select></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">From</label><input type="time" value={entry.from1} onChange={(e) => updateTimeSheetEntry(entry.id, 'from1', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">To</label><input type="time" value={entry.to1} onChange={(e) => updateTimeSheetEntry(entry.id, 'to1', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">From 2</label><input type="time" value={entry.from2} onChange={(e) => updateTimeSheetEntry(entry.id, 'from2', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">To 2</label><input type="time" value={entry.to2} onChange={(e) => updateTimeSheetEntry(entry.id, 'to2', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">Total</label><input type="text" value={entry.total} readOnly className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100" /></div>
                            <div className="flex items-end"><button type="button" onClick={() => removeTimeSheetEntry(entry.id)} className="w-full px-3 py-2 border border-red-300 text-red-700 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">Remove</button></div>
                          </div>
                          <div className="mt-4"><label className="block text-sm font-medium text-gray-700 mb-1">Reason</label><input type="text" value={entry.reason} onChange={(e) => updateTimeSheetEntry(entry.id, 'reason', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="Reason for downtime (if any)" /></div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-center py-8 text-gray-500"><p className="mt-2">No time sheet entries yet. Click "Add Entry" to get started.</p></div>
                  )}
                </div>
              </div>
            )}
            {/* Step 4: Stoppages & Notes */}
            {currentStep === 4 && (
              <div className="space-y-6">
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="text-lg font-medium text-gray-900">Dredger Stoppages</h3>
                    <button type="button" onClick={addStoppageEntry} className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                      <svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" /></svg>Add Stoppage
                    </button>
                  </div>
                  {stoppageEntries.length > 0 ? (
                    <div className="space-y-4">
                      {stoppageEntries.map((entry) => (
                        <div key={entry.id} className="bg-gray-50 p-4 rounded-lg">
                          <div className="grid grid-cols-1 md:grid-cols-6 gap-4">
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">From</label><input type="time" value={entry.from} onChange={(e) => updateStoppageEntry(entry.id, 'from', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">To</label><input type="time" value={entry.to} onChange={(e) => updateStoppageEntry(entry.id, 'to', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" /></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">Total</label><input type="text" value={entry.total} readOnly className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm bg-gray-100" /></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">Reason</label><select value={entry.reason} onChange={(e) => updateStoppageEntry(entry.id, 'reason', e.target.value)} disabled={entry.responsible === 'reclamation'} className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 ${entry.responsible === 'reclamation' ? 'bg-gray-100 text-gray-500 cursor-not-allowed border-gray-300' : 'border-gray-300'}`}><option value="">None</option><option value="maintenance">Maintenance</option><option value="shift">Shift</option><option value="lubrication">Lubrication</option><option value="check">Check</option></select></div>
                            <div><label className="block text-sm font-medium text-gray-700 mb-1">Responsible</label><select value={entry.responsible} onChange={(e) => updateStoppageEntry(entry.id, 'responsible', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"><option value="reclamation">Reclamation</option><option value="dredger">Dredger</option></select></div>
                            <div className="flex items-end"><button type="button" onClick={() => removeStoppageEntry(entry.id)} className="w-full px-3 py-2 border border-red-300 text-red-700 rounded-md hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">Remove</button></div>
                          </div>
                          <div className="mt-4"><label className="block text-sm font-medium text-gray-700 mb-1">Notes {entry.responsible === 'reclamation' && <span className="text-red-500">*</span>}</label><input type="text" value={entry.note} onChange={(e) => updateStoppageEntry(entry.id, 'note', e.target.value)} className={`w-full px-3 py-2 border rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 ${entry.responsible === 'reclamation' && !entry.note.trim() ? 'border-red-300 bg-red-50' : 'border-gray-300'}`} placeholder={entry.responsible === 'reclamation' ? 'Notes required for reclamation stoppages' : 'Additional notes'} /></div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-center py-8 text-gray-500"><p className="mt-2">No stoppages recorded. Click "Add Stoppage" if there were any.</p></div>
                  )}
                </div>
                <div>
                  <label htmlFor="notes" className="block text-sm font-medium text-gray-700 mb-2">Additional Notes & Comments</label>
                  <textarea id="notes" name="notes" rows={4} value={formData.notes} onChange={(e) => updateFormData('notes', e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" placeholder="Enter any additional notes or comments about the operation..." />
                </div>
              </div>
            )}
            {/* Error Message */}
            {actionData?.errors?.form && (
              <div className="mt-4 p-4 bg-red-50 border border-red-200 rounded-md">
                <div className="flex">
                  <svg className="h-5 w-5 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <div className="ml-3">
                    <p className="text-sm text-red-800">{actionData.errors.form}</p>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Navigation Buttons */}
          <div className="px-4 sm:px-6 py-4 bg-gray-50 border-t border-gray-200 flex flex-col sm:flex-row sm:justify-between space-y-3 sm:space-y-0">
            <button type="button" onClick={prevStep} disabled={currentStep === 1} className={`inline-flex items-center justify-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium ${currentStep === 1 ? 'text-gray-400 bg-gray-100 cursor-not-allowed' : 'text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500'}`}>
              <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" /></svg>Previous
            </button>

            <div className="flex space-x-3">
              {currentStep < totalSteps ? (
                <button type="button" onClick={(e) => nextStep(e)} disabled={!isCurrentStepValid()} className={`flex-1 sm:flex-none inline-flex items-center justify-center px-4 py-2 border border-transparent text-sm font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 ${!isCurrentStepValid() ? 'text-gray-400 bg-gray-300 cursor-not-allowed' : 'text-white bg-indigo-600 hover:bg-indigo-700 focus:ring-indigo-500'}`}>
                  Next<svg className="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" /></svg>
                </button>
              ) : (
                <button type="submit" disabled={isSubmitting} className="flex-1 sm:flex-none inline-flex items-center justify-center px-6 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50 disabled:cursor-not-allowed">
                  {isSubmitting ? (
                    <>
                      <svg className="animate-spin -ml-1 mr-3 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>Creating Report...
                    </>
                  ) : (
                    <>
                      <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>Create Report
                    </>
                  )}
                </button>
              )}
            </div>
          </div>

          {/* Hidden inputs for dynamic data */}
          <input type="hidden" name="timeSheetData" value={JSON.stringify(timeSheetEntries)} />
          <input type="hidden" name="stoppagesData" value={JSON.stringify(stoppageEntries)} />
          <input type="hidden" name="workersList" value={JSON.stringify(selectedWorkers)} />

          {/* Hidden inputs for form data from all steps */}
          {currentStep !== 1 && (
            <>
              <input type="hidden" name="createdDate" value={formData.createdDate} />
              <input type="hidden" name="shift" value={formData.shift} />
              <input type="hidden" name="areaId" value={formData.areaId} />
              <input type="hidden" name="dredgerLocationId" value={formData.dredgerLocationId} />
              <input type="hidden" name="reclamationLocationId" value={formData.reclamationLocationId} />
            </>
          )}
          {currentStep !== 2 && (
            <>
              <input type="hidden" name="dredgerLineLength" value={formData.dredgerLineLength} />
              <input type="hidden" name="shoreConnection" value={formData.shoreConnection} />
              <input type="hidden" name="reclamationHeightBase" value={formData.reclamationHeightBase} />
              <input type="hidden" name="reclamationHeightExtra" value={formData.reclamationHeightExtra} />
              <input type="hidden" name="pipelineMain" value={formData.pipelineMain} />
              <input type="hidden" name="pipelineExt1" value={formData.pipelineExt1} />
              <input type="hidden" name="pipelineReserve" value={formData.pipelineReserve} />
              <input type="hidden" name="pipelineExt2" value={formData.pipelineExt2} />
            </>
          )}
          {currentStep !== 3 && (
            <>
              <input type="hidden" name="statsDozers" value={formData.statsDozers} />
              <input type="hidden" name="statsExc" value={formData.statsExc} />
              <input type="hidden" name="statsLoaders" value={formData.statsLoaders} />
              <input type="hidden" name="statsForeman" value={formData.statsForeman} />
              <input type="hidden" name="statsLaborer" value={formData.statsLaborer} />
            </>
          )}
          {currentStep !== 4 && (
            <input type="hidden" name="notes" value={formData.notes} />
          )}
        </Form>

        {/* Zero Equipment Confirmation Modal */}
        {showZeroEquipmentConfirm && (
          <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
            <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
              <div className="mt-3 text-center">
                <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-yellow-100">
                  <svg className="h-6 w-6 text-yellow-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
                  </svg>
                </div>
                <h3 className="text-lg leading-6 font-medium text-gray-900 mt-4">No Equipment Added</h3>
                <div className="mt-2 px-7 py-3">
                  <p className="text-sm text-gray-500">
                    You haven't added any equipment to the time sheet. This means all equipment counts (Dozers, Excavators, Loaders) will be 0.
                  </p>
                  <p className="text-sm text-gray-500 mt-2">
                    Are you sure you want to continue without any equipment entries?
                  </p>
                </div>
                <div className="flex gap-3 mt-4">
                  <button
                    onClick={cancelZeroEquipmentConfirm}
                    className="flex-1 px-4 py-2 bg-gray-500 text-white text-base font-medium rounded-md shadow-sm hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-gray-300"
                  >
                    Go Back
                  </button>
                  <button
                    onClick={confirmZeroEquipmentAndProceed}
                    className="flex-1 px-4 py-2 bg-yellow-600 text-white text-base font-medium rounded-md shadow-sm hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-yellow-300"
                  >
                    Continue Anyway
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}