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 { 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { Plus, Trash2, Save, Send } from "lucide-react";
import { PersianDatePicker } from "./PersianDatePicker";
import DigitalSignature from "./DigitalSignature";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { useAuth } from "@/hooks/useAuth";
import FormDelegation from "./FormDelegation";

interface PartRow {
  partName: string;
  requestedAmount: string;
  unit: string;
}

interface EngineeringFormData {
  suggestedSupplier: string;
  drawingCode: string;
  sentDocuments: string;
  documentSendDate: string;
  needDate: string;
  productName: string;
  supplyExecutive: string;
  supplyOrder: string;
  newProductDevPhase: string;
  issueReason: string;
  indicatorNumber: string;
  actionNumber: string;
  engineeringDate: string;
  previousFormIndicator: string;
  projectCostCenterCode: string;
  expertApproval: string;
  managerApproval: string;
}

const engineeringFormSchema = z.object({
  suggestedSupplier: z.string().optional(),
  drawingCode: z.string().optional(),
  sentDocuments: z.string().optional(),
  documentSendDate: z.string().optional(),
  needDate: z.string().optional(),
  productName: z.string().min(1, "نام محصول الزامی است"),
  supplyExecutive: z.string().optional(),
  supplyOrder: z.string().optional(),
  newProductDevPhase: z.string().optional(),
  issueReason: z.string().optional(),
  indicatorNumber: z.string().min(1, "شماره اندیکاتور الزامی است"),
  actionNumber: z.string().optional(),
  engineeringDate: z.string().optional(),
  previousFormIndicator: z.string().optional(),
  projectCostCenterCode: z.string().optional(),
  expertApproval: z.string().optional(),
  managerApproval: z.string().optional(),
});

interface EngineeringFormProps {
  initialData?: Partial<EngineeringFormData>;
  partsData?: PartRow[];
  onSave: (data: EngineeringFormData, parts: PartRow[]) => void;
  onSubmit: (data: EngineeringFormData, parts: PartRow[]) => void;
  isLoading?: boolean;
  canEdit?: boolean;
  formId?: string;
  onBeforeDelegate?: () => Promise<void>;
}

export default function EngineeringForm({
  initialData,
  partsData = [],
  onSave,
  onSubmit,
  isLoading = false,
  canEdit = true,
  formId,
  onBeforeDelegate
}: EngineeringFormProps) {
  const { toast } = useToast();
  const { user } = useAuth();
  const queryClient = useQueryClient();

  // Mutation for applying digital signatures
  const applySignatureMutation = useMutation({
    mutationFn: async ({ fieldName }: { fieldName: string }) => {
      if (!formId) throw new Error("فرم ID موجود نیست");
      console.log(`Applying signature to field: ${fieldName} for form: ${formId}`);
      
      const response = await apiRequest("POST", `/api/forms/${formId}/apply-signature`, { fieldName });
      if (!response.ok) {
        const errorText = await response.text();
        console.error("Signature API error:", errorText);
        throw new Error(`Server error: ${response.status} - ${errorText}`);
      }
      return response.json();
    },
    onSuccess: (data) => {
      console.log("Signature applied successfully:", data);
      toast({
        title: "موفقیت",
        description: "امضای دیجیتال با موفقیت اعمال شد",
      });
      queryClient.invalidateQueries({ queryKey: [`/api/forms/${formId}`] });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
    },
    onError: (error: any) => {
      console.error("Signature mutation error:", error);
      toast({
        title: "خطا",
        description: error.message || "خطا در اعمال امضای دیجیتال",
        variant: "destructive",
      });
    }
  });

  const [parts, setParts] = useState<PartRow[]>(
    partsData.length > 0 ? partsData : [
      { partName: "", requestedAmount: "", unit: "" },
      { partName: "", requestedAmount: "", unit: "" },
      { partName: "", requestedAmount: "", unit: "" },
      { partName: "", requestedAmount: "", unit: "" },
      { partName: "", requestedAmount: "", unit: "" }
    ]
  );

  const form = useForm<EngineeringFormData>({
    resolver: zodResolver(engineeringFormSchema),
    defaultValues: {
      suggestedSupplier: initialData?.suggestedSupplier || "",
      drawingCode: initialData?.drawingCode || "",
      sentDocuments: initialData?.sentDocuments || "",
      documentSendDate: initialData?.documentSendDate || "",
      needDate: initialData?.needDate || "",
      productName: initialData?.productName || "",
      supplyExecutive: initialData?.supplyExecutive || "",
      supplyOrder: initialData?.supplyOrder || "",
      newProductDevPhase: initialData?.newProductDevPhase || "",
      issueReason: initialData?.issueReason || "",
      indicatorNumber: initialData?.indicatorNumber || "",
      actionNumber: initialData?.actionNumber || "",
      engineeringDate: initialData?.engineeringDate || "",
      previousFormIndicator: initialData?.previousFormIndicator || "",
      projectCostCenterCode: initialData?.projectCostCenterCode || "",
      expertApproval: initialData?.expertApproval || "",
      managerApproval: initialData?.managerApproval || "",
    },
  });

  const handleSave = async (data: EngineeringFormData) => {
    if (!formId) return;
    
    try {
      // Prepare data with parts table
      const saveData = {
        ...data,
        partsTable: parts
      };
      
      // Debug log to verify all new fields are included
      console.log("Engineering form save data:", {
        actionNumber: saveData.actionNumber,
        engineeringDate: saveData.engineeringDate,
        newProductDevPhase: saveData.newProductDevPhase,
        issueReason: saveData.issueReason,
        partsTable: saveData.partsTable
      });
      
      // Call the save API endpoint
      const response = await apiRequest("PUT", `/api/forms/${formId}/save`, { data: saveData });
      if (!response.ok) {
        throw new Error("خطا در ذخیره فرم");
      }
      
      console.log("Engineering form saved successfully");
      
      // Also call the parent onSave callback
      onSave(data, parts);
    } catch (error) {
      console.error("Error saving engineering form:", error);
    }
  };

  const handleSubmit = (data: EngineeringFormData) => {
    onSubmit(data, parts);
  };

  const updatePart = (index: number, field: keyof PartRow, value: string) => {
    if (!canEdit) return;
    const newParts = [...parts];
    newParts[index] = { ...newParts[index], [field]: value };
    setParts(newParts);
  };

  const addPart = () => {
    if (!canEdit) return;
    setParts([...parts, { partName: "", requestedAmount: "", unit: "" }]);
  };

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

  return (
    <Card className="w-full">
      <CardHeader className="bg-yellow-100 border-b">
        <CardTitle className="text-center text-lg font-bold">مهندسی محصول</CardTitle>
      </CardHeader>
      <CardContent className="p-6">
        <Form {...form}>
          <form className="space-y-6">
            {/* Basic Information Fields */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="productName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>نام محصول:</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        placeholder="نام محصول را وارد کنید"
                        disabled={!canEdit}
                        className="text-right"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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

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

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

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

              <FormField
                control={form.control}
                name="newProductDevPhase"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>فاز تکوین محصول جدید:</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value} disabled={!canEdit}>
                      <FormControl>
                        <SelectTrigger className="text-right">
                          <SelectValue placeholder="انتخاب فاز تکوین محصول جدید" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="نمونه اولیه">نمونه اولیه</SelectItem>
                        <SelectItem value="یکروز خط">یکروز خط</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="issueReason"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>علت صدور:</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value} disabled={!canEdit}>
                      <FormControl>
                        <SelectTrigger className="text-right">
                          <SelectValue placeholder="انتخاب علت صدور" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="تکوین محصول جدید (پروژه)">تکوین محصول جدید (پروژه)</SelectItem>
                        <SelectItem value="تغییرات مهندسی">تغییرات مهندسی</SelectItem>
                        <SelectItem value="تامین کننده جدید">تامین کننده جدید</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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

              <FormField
                control={form.control}
                name="supplyExecutive"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>مجری تامین:</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value} disabled={!canEdit}>
                      <FormControl>
                        <SelectTrigger className="text-right">
                          <SelectValue placeholder="انتخاب مجری تامین" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="خرید داخلی">خرید داخلی</SelectItem>
                        <SelectItem value="خرید خارجی">خرید خارجی</SelectItem>
                        <SelectItem value="لجستیک">لجستیک</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="supplyOrder"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>مرتبه تامین:</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value} disabled={!canEdit}>
                      <FormControl>
                        <SelectTrigger className="text-right">
                          <SelectValue placeholder="انتخاب مرتبه تامین" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="تامین اول">تامین اول</SelectItem>
                        <SelectItem value="تامین مجدد">تامین مجدد</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

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

              <FormField
                control={form.control}
                name="needDate"
                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>

            <Separator />

            {/* Parts Table */}
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-medium">جدول قطعات</h3>
                {canEdit && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={addPart}
                    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>
                    {canEdit && <TableHead className="text-center">عملیات</TableHead>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {parts.map((part, index) => (
                    <TableRow key={index}>
                      <TableCell>
                        <Input
                          value={part.partName}
                          onChange={(e) => updatePart(index, "partName", e.target.value)}
                          placeholder="نام قطعه"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={part.requestedAmount}
                          onChange={(e) => updatePart(index, "requestedAmount", e.target.value)}
                          placeholder="مقدار درخواستی"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={part.unit}
                          onChange={(e) => updatePart(index, "unit", e.target.value)}
                          placeholder="واحد"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      {canEdit && (
                        <TableCell>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => removePart(index)}
                            disabled={parts.length <= 1}
                            className="h-8 w-8 p-0"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            <Separator />

            {/* Approval Sections - Always show signatures regardless of current user */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <DigitalSignature
                title="تایید کارشناس/سرپرست"
                signedBy={initialData?.expertApproval ? "امضا شده" : undefined}
                signedAt={initialData?.expertApproval ? new Date().toISOString() : undefined}
                signatureImageUrl={(initialData as any)?.expertApprovalImageUrl}
                currentApprovalText={initialData?.expertApproval}
                onSign={async (signatureData) => {
                  await applySignatureMutation.mutateAsync({ fieldName: "expertApproval" });
                }}
                required={true}
                isEditable={canEdit && !!formId}
                signatureType="expert"
              />

              <DigitalSignature
                title="تایید مدیر/جانشین"
                signedBy={initialData?.managerApproval ? "امضا شده" : undefined}
                signedAt={initialData?.managerApproval ? new Date().toISOString() : undefined}
                signatureImageUrl={(initialData as any)?.managerApprovalImageUrl}
                currentApprovalText={initialData?.managerApproval}
                onSign={async (signatureData) => {
                  await applySignatureMutation.mutateAsync({ fieldName: "managerApproval" });
                }}
                required={true}
                isEditable={canEdit && !!formId}
                signatureType="manager"
              />
            </div>

            {/* Action Buttons */}
            {canEdit && (
              <div className="flex gap-4 justify-end pt-4">
                <FormDelegation
                  formId={formId || ""}
                  currentDepartment="engineering"
                  onBeforeDelegate={async () => {
                    try {
                      // Get current form values and save them
                      const currentValues = form.getValues();
                      console.log("Engineering form values before delegation:", currentValues);
                      await handleSave(currentValues);
                    } catch (error) {
                      console.error("Error saving form before delegation:", error);
                    }
                  }}
                />
              </div>
            )}
          </form>
        </Form>
      </CardContent>
    </Card>
  );
}