import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
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 { Separator } from "@/components/ui/separator";
import { Plus, Trash2, Save, Send } from "lucide-react";
import { PersianDatePicker } from "./PersianDatePicker";
import DigitalSignature from "./DigitalSignature";
import { useAuth } from "@/hooks/useAuth";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import FormDelegation from "./FormDelegation";

interface ReceivedRow {
  receivedAmount: string;
  unit: string;
}

interface CommercialFormData {
  commercialSupplierNameCode: string;
  commercialSampleSendDate: string;
  commercialBillNumber: string;
  commercialShipmentCode: string;
  commercialContractorCertificate: string;
  commercialExpertApproval: string;
  commercialManagerApproval: string;
}

const commercialFormSchema = z.object({
  commercialSupplierNameCode: z.string().min(1, "نام/کد تامین کننده الزامی است"),
  commercialSampleSendDate: z.string().min(1, "تاریخ ارسال نمونه الزامی است"),
  commercialBillNumber: z.string().min(1, "شماره بارنامه الزامی است"),
  commercialShipmentCode: z.string().min(1, "کد محموله الزامی است"),
  commercialContractorCertificate: z.string().min(1, "گواهی پیمانکار الزامی است"),
  commercialExpertApproval: z.string().optional(),
  commercialManagerApproval: z.string().optional(),
});

interface CommercialFormProps {
  initialData?: Partial<CommercialFormData>;
  receivedData?: ReceivedRow[];
  onSave: (data: CommercialFormData, received: ReceivedRow[]) => void;
  onSubmit: (data: CommercialFormData, received: ReceivedRow[]) => void;
  isLoading?: boolean;
  canEdit?: boolean;
  formId?: string;
  onBeforeDelegate?: () => Promise<void>;
}

export default function CommercialForm({
  initialData,
  receivedData = [],
  onSave,
  onSubmit,
  isLoading = false,
  canEdit = true,
  formId,
  onBeforeDelegate
}: CommercialFormProps) {
  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}`);
      
      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);
      queryClient.invalidateQueries({ queryKey: [`/api/forms/${formId}`] });
      queryClient.invalidateQueries({ queryKey: ["/api/forms"] });
    },
    onError: (error) => {
      console.error("Signature mutation error:", error);
    }
  });
  const [received, setReceived] = useState<ReceivedRow[]>(
    receivedData.length > 0 ? receivedData : [
      { receivedAmount: "", unit: "" },
      { receivedAmount: "", unit: "" },
      { receivedAmount: "", unit: "" },
      { receivedAmount: "", unit: "" },
      { receivedAmount: "", unit: "" }
    ]
  );

  const form = useForm<CommercialFormData>({
    resolver: zodResolver(commercialFormSchema),
    defaultValues: {
      commercialSupplierNameCode: initialData?.commercialSupplierNameCode || "",
      commercialSampleSendDate: initialData?.commercialSampleSendDate || "",
      commercialBillNumber: initialData?.commercialBillNumber || "",
      commercialShipmentCode: initialData?.commercialShipmentCode || "",
      commercialContractorCertificate: initialData?.commercialContractorCertificate || "",
      commercialExpertApproval: initialData?.commercialExpertApproval || "",
      commercialManagerApproval: initialData?.commercialManagerApproval || "",
    },
  });

  const handleSave = async (data: CommercialFormData) => {
    if (!formId) return;
    
    try {
      // Prepare data with received table
      const saveData = {
        ...data,
        commercialReceivedTable: received
      };
      
      // Call the save API endpoint
      const response = await apiRequest("PUT", `/api/forms/${formId}/save`, { data: saveData });
      if (!response.ok) {
        throw new Error("خطا در ذخیره فرم");
      }
      
      // Also call the parent onSave callback
      onSave(data, received);
    } catch (error) {
      console.error("Error saving commercial form:", error);
    }
  };

  const handleSubmit = (data: CommercialFormData) => {
    onSubmit(data, received);
  };

  const updateReceived = (index: number, field: keyof ReceivedRow, value: string) => {
    if (!canEdit) return;
    const newReceived = [...received];
    newReceived[index] = { ...newReceived[index], [field]: value };
    setReceived(newReceived);
  };

  const addReceivedRow = () => {
    if (!canEdit) return;
    setReceived([...received, { receivedAmount: "", unit: "" }]);
  };

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

  return (
    <Card className="w-full">
      <CardHeader className="bg-blue-100 border-b">
        <CardTitle className="text-center text-lg font-bold">بازرگانی</CardTitle>
      </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="commercialSupplierNameCode"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>نام/کد تامین کننده:</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        disabled={!canEdit}
                        className="text-right"
                        placeholder="نام یا کد تامین کننده"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="commercialSampleSendDate"
                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="commercialBillNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>شماره بارنامه:</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        disabled={!canEdit}
                        className="text-right"
                        placeholder="شماره بارنامه"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

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

              <FormField
                control={form.control}
                name="commercialContractorCertificate"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>گواهی پیمانکار:</FormLabel>
                    <FormControl>
                      <Input
                        {...field}
                        disabled={!canEdit}
                        className="text-right"
                        placeholder="گواهی پیمانکار"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <Separator />

            {/* Received Amount 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={addReceivedRow}
                    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>
                    {canEdit && <TableHead className="text-center">عملیات</TableHead>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {received.map((item, index) => (
                    <TableRow key={index}>
                      <TableCell>
                        <Input
                          value={item.receivedAmount}
                          onChange={(e) => updateReceived(index, 'receivedAmount', e.target.value)}
                          placeholder="مقدار دریافتی"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.unit}
                          onChange={(e) => updateReceived(index, 'unit', e.target.value)}
                          placeholder="واحد"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      {canEdit && (
                        <TableCell>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => removeReceivedRow(index)}
                            disabled={received.length <= 1}
                            className="h-8 w-8 p-0"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            <Separator />

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

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

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

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