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 { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { Save, Send, Archive } from "lucide-react";
import { PersianDatePicker } from "./PersianDatePicker";
import DigitalSignature from "./DigitalSignature";
import FormDelegation from "./FormDelegation";

interface WarehouseFormData {
  warehouseDeliveryDate: string;
  warehouseHealthyCount: string;
  warehouseHealthyUnit: string;
  warehouseWasteCount: string;
  warehouseWasteUnit: string;
  warehouseExpertApproval: string;
  warehouseExpertApprovalImageUrl?: string;
}

const warehouseFormSchema = z.object({
  warehouseDeliveryDate: z.string().optional(),
  warehouseHealthyCount: z.string().optional(),
  warehouseHealthyUnit: z.string().optional(),
  warehouseWasteCount: z.string().optional(),
  warehouseWasteUnit: z.string().optional(),
  warehouseExpertApproval: z.string().optional(),
});

interface WarehouseFormProps {
  initialData?: Partial<WarehouseFormData>;
  onSave: (data: WarehouseFormData) => void;
  onSubmit: (data: WarehouseFormData) => void;
  onArchive?: (data: WarehouseFormData) => void;
  isLoading?: boolean;
  canEdit?: boolean;
  formId?: string;
  onBeforeDelegate?: () => Promise<void>;
}

export default function WarehouseForm({
  initialData,
  onSave,
  onSubmit,
  onArchive,
  isLoading = false,
  canEdit = true,
  formId
}: WarehouseFormProps) {
  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 form = useForm<WarehouseFormData>({
    resolver: zodResolver(warehouseFormSchema),
    defaultValues: {
      warehouseDeliveryDate: initialData?.warehouseDeliveryDate || "",
      warehouseHealthyCount: initialData?.warehouseHealthyCount || "",
      warehouseHealthyUnit: initialData?.warehouseHealthyUnit || "",
      warehouseWasteCount: initialData?.warehouseWasteCount || "",
      warehouseWasteUnit: initialData?.warehouseWasteUnit || "",
      warehouseExpertApproval: initialData?.warehouseExpertApproval || "",
    },
  });

  const handleSave = async (data: WarehouseFormData) => {
    if (!formId) return;
    
    try {
      const response = await apiRequest("PUT", `/api/forms/${formId}/save`, { data });
      if (!response.ok) {
        throw new Error("خطا در ذخیره فرم");
      }
      
      onSave(data);
    } catch (error) {
      console.error("Error saving warehouse form:", error);
    }
  };

  const handleSubmit = (data: WarehouseFormData) => {
    onSubmit(data);
  };

  const handleArchive = (data: WarehouseFormData) => {
    if (onArchive) {
      onArchive(data);
    }
  };

  return (
    <Card className="w-full">
      <CardHeader className="bg-indigo-100 border-b">
        <CardTitle className="text-center text-lg font-bold">انبار</CardTitle>
      </CardHeader>
      <CardContent className="p-6">
        <Form {...form}>
          <form className="space-y-6">
            {/* Date Field */}
            <div className="space-y-4">
              <FormField
                control={form.control}
                name="warehouseDeliveryDate"
                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 />

            {/* Healthy Items Section */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-green-700">اقلام سالم</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="warehouseHealthyCount"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>تعداد سالم:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="تعداد سالم"
                          type="number"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

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

            <Separator />

            {/* Waste Items Section */}
            <div className="space-y-4">
              <h3 className="text-lg font-medium text-red-700">ضایعات</h3>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="warehouseWasteCount"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>تعداد ضایعات:</FormLabel>
                      <FormControl>
                        <Input
                          {...field}
                          disabled={!canEdit}
                          className="text-right"
                          placeholder="تعداد ضایعات"
                          type="number"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

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

            <Separator />

            {/* Expert Approval Section */}
            <div className="flex justify-center">
              <Card className="bg-orange-50 w-full max-w-md">
                <CardHeader className="pb-3">
                  <CardTitle className="text-center text-sm">تایید کارشناس/سرپرست</CardTitle>
                </CardHeader>
                <CardContent>
                  <DigitalSignature
                    title="تایید کارشناس/سرپرست"
                    signedBy={initialData?.warehouseExpertApproval}
                    signatureImageUrl={(initialData as any)?.warehouseExpertApprovalImageUrl}
                    onSign={(data) => applySignatureMutation.mutate({ fieldName: "warehouseExpertApproval" })}
                    signatureType="expert"
                    isEditable={canEdit}
                  />
                </CardContent>
              </Card>
            </div>

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

                <Button
                  type="button"
                  variant="default"
                  onClick={() => form.handleSubmit(handleArchive)()}
                  disabled={isLoading}
                  className="flex items-center gap-2 bg-green-600 hover:bg-green-700"
                >
                  <Archive className="h-4 w-4" />
                  اتمام فرم
                </Button>
                <FormDelegation
                  formId={formId || ""}
                  currentDepartment="warehouse"
                  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>
  );
}