import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { apiRequest } from '@/lib/queryClient';
import { useAuth } from '@/hooks/useAuth';
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Plus, Trash2, Save, Send } from "lucide-react";
import { PersianDatePicker } from "./PersianDatePicker";
import DigitalSignature from "./DigitalSignature";
import FormDelegation from "./FormDelegation";

interface LaboratoryTestRow {
  testName: string;
  testMethod: string;
  testResult: string;
  partStatus: string; // وضعیت قطعه
  comments: string; // ملاحظات
}

interface PartStatusRow {
  partName: string;
  finalStatus: string; // "OK", "NOT OK", "مشروط"
}

interface DimensionalMeasurementRow {
  controlParameter: string; // پارامتر کنترلی
  acceptanceRange: string; // حدود پذیرش
  sampleNumber: string; // شماره نمونه
  comments: string; // توضیحات
}

interface LaboratoryFormData {
  laboratorySpecialStorageConditions: string;
  laboratoryExecutionDate: string;
  laboratoryFinalStatus: string;
  laboratoryTestRequestNumber: string; // شماره درخواست آزمایش
  laboratoryTestRequestDate: string; // تاریخ درخواست
  laboratoryExpertApproval: string;
  laboratoryManagerApproval: string;
  laboratoryExpertApprovalImageUrl?: string;
  laboratoryManagerApprovalImageUrl?: string;
  
  // Dimensional measurement fields
  dimensionalPartName: string;
  dimensionalLotCode: string;
  dimensionalDrawingTestNumber: string;
  dimensionalSupplier: string;
  dimensionalSampleSupplyNumber: string;
  dimensionalSpecialStorageConditions: string;
  dimensionalLotStatus: string; // وضعیت محموله
}

const laboratoryFormSchema = z.object({
  laboratorySpecialStorageConditions: z.string().min(1, "شرایط خاص نگهداری الزامی است"),
  laboratoryExecutionDate: z.string().min(1, "تاریخ انجام الزامی است"),
  laboratoryFinalStatus: z.enum(["OK", "N.OK", "مشروط"], {
    required_error: "انتخاب وضعیت نهایی قطعه الزامی است",
  }),
  laboratoryTestRequestNumber: z.string().optional(),
  laboratoryTestRequestDate: z.string().optional(),
  laboratoryExpertApproval: z.string().optional(),
  laboratoryManagerApproval: z.string().optional(),
  
  // Dimensional measurement fields
  dimensionalPartName: z.string().optional(),
  dimensionalLotCode: z.string().optional(),
  dimensionalDrawingTestNumber: z.string().optional(),
  dimensionalSupplier: z.string().optional(),
  dimensionalSampleSupplyNumber: z.string().optional(),
  dimensionalSpecialStorageConditions: z.string().optional(),
  dimensionalLotStatus: z.string().optional(),
});

interface LaboratoryFormProps {
  initialData?: Partial<LaboratoryFormData>;
  testsData?: LaboratoryTestRow[];
  partsData?: { partName: string; requestedAmount: string; unit: string; }[]; // Parts from engineering section
  partsStatusData?: PartStatusRow[];
  dimensionalMeasurementsData?: DimensionalMeasurementRow[];
  onSave: (data: LaboratoryFormData, tests: LaboratoryTestRow[], partsStatus: PartStatusRow[], dimensionalMeasurements: DimensionalMeasurementRow[]) => void;
  onSubmit: (data: LaboratoryFormData, tests: LaboratoryTestRow[], partsStatus: PartStatusRow[], dimensionalMeasurements: DimensionalMeasurementRow[]) => void;
  isLoading?: boolean;
  canEdit?: boolean;
  formId?: string;
  onBeforeDelegate?: () => Promise<void>;
}

export default function LaboratoryForm({
  initialData,
  testsData = [],
  partsData = [],
  partsStatusData = [],
  dimensionalMeasurementsData = [],
  onSave,
  onSubmit,
  isLoading = false,
  canEdit = true,
  formId
}: LaboratoryFormProps) {
  const { user } = useAuth();
  const queryClient = useQueryClient();

  const applySignatureMutation = useMutation({
    mutationFn: async ({ fieldName }: { fieldName: string }) => {
      if (!formId) throw new Error("فرم ID موجود نیست");
      console.log(`Applying signature to field: ${fieldName} for form: ${formId}`);
      
      try {
        const response = await apiRequest("POST", `/api/forms/${formId}/apply-signature`, { fieldName });
        console.log("API Response status:", response.status);
        
        if (!response.ok) {
          const errorText = await response.text();
          console.error("Signature API error:", errorText);
          throw new Error(`Server error: ${response.status} - ${errorText}`);
        }
        
        const result = await response.json();
        console.log("API Response data:", result);
        return result;
      } catch (error) {
        console.error("Request failed:", error);
        throw error;
      }
    },
    onSuccess: (data) => {
      console.log("Signature applied successfully:", data);
      queryClient.invalidateQueries({ queryKey: [`/api/forms/${formId}`] });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
    },
    onError: (error) => {
      console.error("Signature mutation error:", error);
      // خطا را فقط در console لاگ می‌کنیم، alert نمایش نمی‌دهیم
    }
  });
  const [tests, setTests] = useState<LaboratoryTestRow[]>(
    testsData.length > 0 ? testsData : [
      { testName: "", testMethod: "", testResult: "", partStatus: "", comments: "" },
      { testName: "", testMethod: "", testResult: "", partStatus: "", comments: "" },
      { testName: "", testMethod: "", testResult: "", partStatus: "", comments: "" },
      { testName: "", testMethod: "", testResult: "", partStatus: "", comments: "" },
      { testName: "", testMethod: "", testResult: "", partStatus: "", comments: "" }
    ]
  );

  // Initialize parts status based on engineering parts data
  const [partsStatus, setPartsStatus] = useState<PartStatusRow[]>(() => {
    if (partsStatusData.length > 0) {
      return partsStatusData;
    }
    // Create status entries for each part from engineering section
    return partsData.filter(part => part.partName.trim()).map(part => ({
      partName: part.partName,
      finalStatus: ""
    }));
  });

  // Initialize dimensional measurements
  const [dimensionalMeasurements, setDimensionalMeasurements] = useState<DimensionalMeasurementRow[]>(
    dimensionalMeasurementsData.length > 0 ? dimensionalMeasurementsData : [
      { controlParameter: "", acceptanceRange: "", sampleNumber: "", comments: "" },
      { controlParameter: "", acceptanceRange: "", sampleNumber: "", comments: "" },
      { controlParameter: "", acceptanceRange: "", sampleNumber: "", comments: "" },
      { controlParameter: "", acceptanceRange: "", sampleNumber: "", comments: "" },
      { controlParameter: "", acceptanceRange: "", sampleNumber: "", comments: "" }
    ]
  );

  const form = useForm<LaboratoryFormData>({
    resolver: zodResolver(laboratoryFormSchema),
    defaultValues: {
      laboratorySpecialStorageConditions: initialData?.laboratorySpecialStorageConditions || "",
      laboratoryExecutionDate: initialData?.laboratoryExecutionDate || "",
      laboratoryFinalStatus: initialData?.laboratoryFinalStatus || "",
      laboratoryTestRequestNumber: initialData?.laboratoryTestRequestNumber || "",
      laboratoryTestRequestDate: initialData?.laboratoryTestRequestDate || "",
      laboratoryExpertApproval: initialData?.laboratoryExpertApproval || "",
      laboratoryManagerApproval: initialData?.laboratoryManagerApproval || "",
      dimensionalPartName: initialData?.dimensionalPartName || "",
      dimensionalLotCode: initialData?.dimensionalLotCode || "",
      dimensionalDrawingTestNumber: initialData?.dimensionalDrawingTestNumber || "",
      dimensionalSupplier: initialData?.dimensionalSupplier || "",
      dimensionalSampleSupplyNumber: initialData?.dimensionalSampleSupplyNumber || "",
      dimensionalSpecialStorageConditions: initialData?.dimensionalSpecialStorageConditions || "",
      dimensionalLotStatus: initialData?.dimensionalLotStatus || "",
    },
  });

  const handleSave = async (data: LaboratoryFormData) => {
    if (!formId) return;
    
    try {
      const saveData = {
        ...data,
        laboratoryTestsTable: tests,
        laboratoryPartsStatusTable: partsStatus,
        dimensionalMeasurementsTable: dimensionalMeasurements
      };
      
      // Debug log to verify all new fields are included
      console.log("Laboratory form save data:", {
        laboratoryTestRequestNumber: saveData.laboratoryTestRequestNumber,
        laboratoryTestRequestDate: saveData.laboratoryTestRequestDate,
        dimensionalPartName: saveData.dimensionalPartName,
        dimensionalLotCode: saveData.dimensionalLotCode,
        dimensionalLotStatus: saveData.dimensionalLotStatus,
        dimensionalMeasurementsTable: saveData.dimensionalMeasurementsTable
      });
      
      const response = await apiRequest("PUT", `/api/forms/${formId}/save`, { data: saveData });
      if (!response.ok) {
        throw new Error("خطا در ذخیره فرم");
      }
      
      console.log("Laboratory form saved successfully");
      
      onSave(data, tests, partsStatus, dimensionalMeasurements);
    } catch (error) {
      console.error("Error saving laboratory form:", error);
    }
  };

  const handleSubmit = (data: LaboratoryFormData) => {
    onSubmit(data, tests, partsStatus, dimensionalMeasurements);
  };

  const updatePartStatus = (index: number, status: string) => {
    if (!canEdit) return;
    const newPartsStatus = [...partsStatus];
    newPartsStatus[index] = { ...newPartsStatus[index], finalStatus: status };
    setPartsStatus(newPartsStatus);
  };

  const updateTest = (index: number, field: keyof LaboratoryTestRow, value: string) => {
    if (!canEdit) return;
    const newTests = [...tests];
    newTests[index] = { ...newTests[index], [field]: value };
    setTests(newTests);
  };

  const addTestRow = () => {
    if (!canEdit) return;
    setTests([...tests, { testName: "", testMethod: "", testResult: "", partStatus: "", comments: "" }]);
  };

  const removeTestRow = (index: number) => {
    if (!canEdit || tests.length <= 1) return;
    setTests(tests.filter((_, i) => i !== index));
  };

  const updateDimensionalMeasurement = (index: number, field: keyof DimensionalMeasurementRow, value: string) => {
    if (!canEdit) return;
    const newMeasurements = [...dimensionalMeasurements];
    newMeasurements[index] = { ...newMeasurements[index], [field]: value };
    setDimensionalMeasurements(newMeasurements);
  };

  const addDimensionalRow = () => {
    if (!canEdit) return;
    setDimensionalMeasurements([...dimensionalMeasurements, { controlParameter: "", acceptanceRange: "", sampleNumber: "", comments: "" }]);
  };

  const removeDimensionalRow = (index: number) => {
    if (!canEdit || dimensionalMeasurements.length <= 1) return;
    setDimensionalMeasurements(dimensionalMeasurements.filter((_, i) => i !== index));
  };

  return (
    <Card className="w-full">
      <CardHeader className="bg-red-100 border-b">
        <CardTitle className="text-center text-lg font-bold">تست آزمایشگاه</CardTitle>
        <p className="text-center text-sm text-gray-600">(دسترسی ویژه واحد مهندسی)</p>
      </CardHeader>
      <CardContent className="p-6">
        <Form {...form}>
          <form className="space-y-6">
            {/* Form Fields */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="laboratorySpecialStorageConditions"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>شرایط خاص نگهداری:</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        disabled={!canEdit}
                        className="text-right"
                        placeholder="شرایط خاص نگهداری"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="laboratoryExecutionDate"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>تاریخ انجام:</FormLabel>
                    <FormControl>
                      <PersianDatePicker
                        value={field.value}
                        onChange={field.onChange}
                        placeholder="انتخاب تاریخ انجام"
                        className={!canEdit ? "opacity-50 pointer-events-none" : ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            {/* Parts Status Table */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium">وضعیت نهایی قطعات</h3>
              {partsStatus.length > 0 ? (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-center">نام قطعه</TableHead>
                      <TableHead className="text-center">وضعیت نهایی</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {partsStatus.map((item, index) => (
                      <TableRow key={index}>
                        <TableCell className="text-center">
                          <span className="font-medium">{item.partName}</span>
                        </TableCell>
                        <TableCell className="text-center">
                          <Select
                            value={item.finalStatus}
                            onValueChange={(value) => updatePartStatus(index, value)}
                            disabled={!canEdit}
                          >
                            <SelectTrigger className="w-full">
                              <SelectValue placeholder="انتخاب وضعیت" />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="OK">OK</SelectItem>
                              <SelectItem value="NOT OK">NOT OK</SelectItem>
                              <SelectItem value="مشروط">مشروط</SelectItem>
                            </SelectContent>
                          </Select>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              ) : (
                <div className="text-center text-gray-500 py-4">
                  هیچ قطعه‌ای از بخش مهندسی دریافت نشده است
                </div>
              )}
            </div>

            <Separator />

            {/* Tests Table */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium">جدول آزمون‌ها</h3>
              
              {/* Test Request Fields Above Table */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="laboratoryTestRequestNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>شماره درخواست آزمایش:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="شماره درخواست آزمایش"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="laboratoryTestRequestDate"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>تاریخ درخواست:</FormLabel>
                      <FormControl>
                        <PersianDatePicker
                          value={field.value}
                          onChange={field.onChange}
                          placeholder="انتخاب تاریخ درخواست"
                          className={!canEdit ? "opacity-50 pointer-events-none" : ""}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <div className="flex items-center justify-between">
                <h4 className="text-md font-medium">جدول آزمون‌ها</h4>
                {canEdit && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={addTestRow}
                    className="flex items-center gap-2"
                  >
                    <Plus className="h-4 w-4" />
                    افزودن ردیف
                  </Button>
                )}
              </div>

              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="text-center">نام آزمون</TableHead>
                    <TableHead className="text-center">روش آزمون</TableHead>
                    <TableHead className="text-center">نتیجه آزمون</TableHead>
                    <TableHead className="text-center">وضعیت قطعه</TableHead>
                    <TableHead className="text-center">ملاحظات</TableHead>
                    {canEdit && <TableHead className="text-center">عملیات</TableHead>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {tests.map((item, index) => (
                    <TableRow key={index}>
                      <TableCell>
                        <Input
                          value={item.testName}
                          onChange={(e) => updateTest(index, 'testName', e.target.value)}
                          placeholder="نام آزمون"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.testMethod}
                          onChange={(e) => updateTest(index, 'testMethod', e.target.value)}
                          placeholder="روش آزمون"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.testResult}
                          onChange={(e) => updateTest(index, 'testResult', e.target.value)}
                          placeholder="نتیجه آزمون"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.partStatus}
                          onChange={(e) => updateTest(index, 'partStatus', e.target.value)}
                          placeholder="وضعیت قطعه"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.comments}
                          onChange={(e) => updateTest(index, 'comments', e.target.value)}
                          placeholder="ملاحظات"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      {canEdit && (
                        <TableCell>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => removeTestRow(index)}
                            disabled={tests.length <= 1}
                            className="h-8 w-8 p-0"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            <Separator />

            {/* Dimensional Measurement Recording Section */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-center bg-blue-100 p-3 rounded-lg border-2 border-blue-300">
                ثبت مقادیر اندازه گیری ابعادی
              </h3>
              
              {/* Text Fields Outside Table */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <FormField
                  control={form.control}
                  name="dimensionalPartName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>نام قطعه:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="نام قطعه"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="dimensionalLotCode"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>کد محموله:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="کد محموله"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="dimensionalDrawingTestNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>شماره نقشه/طرح تست:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="شماره نقشه/طرح تست"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="dimensionalSupplier"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>تامین کننده:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="تامین کننده"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="dimensionalSampleSupplyNumber"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>شماره تامین نمونه کالا:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="شماره تامین نمونه کالا"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="dimensionalSpecialStorageConditions"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>شرایط خاص نگهداری:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="شرایط خاص نگهداری"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              {/* Dimensional Measurements Table */}
              <div className="space-y-4">
                <div className="flex items-center justify-between">
                  <h4 className="text-md font-medium">جدول ثبت مقادیر اندازه گیری ابعادی</h4>
                  {canEdit && (
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={addDimensionalRow}
                      className="flex items-center gap-2"
                    >
                      <Plus className="h-4 w-4" />
                      افزودن ردیف
                    </Button>
                  )}
                </div>

                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="text-center">پارامتر کنترلی</TableHead>
                      <TableHead className="text-center">حدود پذیرش</TableHead>
                      <TableHead className="text-center">شماره نمونه</TableHead>
                      <TableHead className="text-center">توضیحات</TableHead>
                      {canEdit && <TableHead className="text-center">عملیات</TableHead>}
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {dimensionalMeasurements.map((item, index) => (
                      <TableRow key={index}>
                        <TableCell>
                          <Input
                            value={item.controlParameter}
                            onChange={(e) => updateDimensionalMeasurement(index, 'controlParameter', e.target.value)}
                            placeholder="پارامتر کنترلی"
                            disabled={!canEdit}
                            className="text-right"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={item.acceptanceRange}
                            onChange={(e) => updateDimensionalMeasurement(index, 'acceptanceRange', e.target.value)}
                            placeholder="حدود پذیرش"
                            disabled={!canEdit}
                            className="text-right"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={item.sampleNumber}
                            onChange={(e) => updateDimensionalMeasurement(index, 'sampleNumber', e.target.value)}
                            placeholder="شماره نمونه"
                            disabled={!canEdit}
                            className="text-right"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={item.comments}
                            onChange={(e) => updateDimensionalMeasurement(index, 'comments', e.target.value)}
                            placeholder="توضیحات"
                            disabled={!canEdit}
                            className="text-right"
                          />
                        </TableCell>
                        {canEdit && (
                          <TableCell>
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              onClick={() => removeDimensionalRow(index)}
                              disabled={dimensionalMeasurements.length <= 1}
                              className="h-8 w-8 p-0"
                            >
                              <Trash2 className="h-4 w-4" />
                            </Button>
                          </TableCell>
                        )}
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* Shipment Status Radio Buttons */}
              <div className="space-y-4">
                <FormField
                  control={form.control}
                  name="dimensionalLotStatus"
                  render={({ field }) => (
                    <FormItem className="space-y-3">
                      <FormLabel className="text-md font-medium">وضعیت محموله:</FormLabel>
                      <FormControl>
                        <RadioGroup
                          onValueChange={field.onChange}
                          value={field.value}
                          className="flex gap-8"
                          disabled={!canEdit}
                        >
                          <div className="flex items-center space-x-2 space-x-reverse">
                            <RadioGroupItem value="تایید" id="approved" />
                            <Label htmlFor="approved">تایید</Label>
                          </div>
                          <div className="flex items-center space-x-2 space-x-reverse">
                            <RadioGroupItem value="مردود" id="rejected" />
                            <Label htmlFor="rejected">مردود</Label>
                          </div>
                        </RadioGroup>
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            <Separator />

            {/* Approval Sections */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <Card className="bg-orange-50">
                <CardHeader className="pb-3">
                  <CardTitle className="text-center text-sm">تایید کارشناس/سرپرست</CardTitle>
                </CardHeader>
                <CardContent>
                  <DigitalSignature
                    title="تایید کارشناس/سرپرست"
                    signedBy={initialData?.laboratoryExpertApproval}
                    signatureImageUrl={(initialData as any)?.laboratoryExpertApprovalImageUrl}
                    onSign={(data) => applySignatureMutation.mutate({ fieldName: "laboratoryExpertApproval" })}
                    signatureType="expert"
                    isEditable={canEdit}
                  />
                </CardContent>
              </Card>

              <Card className="bg-green-50">
                <CardHeader className="pb-3">
                  <CardTitle className="text-center text-sm">تایید مدیر/جانشین</CardTitle>
                </CardHeader>
                <CardContent>
                  <DigitalSignature
                    title="تایید مدیر/جانشین"
                    signedBy={initialData?.laboratoryManagerApproval}
                    signatureImageUrl={(initialData as any)?.laboratoryManagerApprovalImageUrl}
                    onSign={(data) => applySignatureMutation.mutate({ fieldName: "laboratoryManagerApproval" })}
                    signatureType="manager"
                    isEditable={canEdit}
                  />
                </CardContent>
              </Card>
            </div>

            {/* Action Buttons */}
            {canEdit && (
              <div className="flex gap-4 justify-end pt-4">

                <FormDelegation
                  formId={formId || ""}
                  currentDepartment="laboratory"
                  onBeforeDelegate={async () => {
                    try {
                      // Get current form values and save them
                      const currentValues = form.getValues();
                      console.log("Laboratory form values before delegation:", currentValues);
                      await handleSave(currentValues);
                    } catch (error) {
                      console.error("Error saving form before delegation:", error);
                    }
                  }}
                />
              </div>
            )}
          </form>
        </Form>
      </CardContent>
    </Card>
  );
}