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 QualityPartsRow {
  partCode: string;
  unit: string;
  materialType: string;
}

interface QualityFormData {
  qualityExecutionDate: string;
  qualityManagerApproval: string;
  qualityManagerApprovalImageUrl?: string;
}

const qualityFormSchema = z.object({
  qualityExecutionDate: z.string().min(1, "تاریخ انجام الزامی است"),
  qualityManagerApproval: z.string().optional(),
});

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

export default function QualityForm({
  initialData,
  partsData = [],
  onSave,
  onSubmit,
  isLoading = false,
  canEdit = true,
  formId
}: QualityFormProps) {
  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 [parts, setParts] = useState<QualityPartsRow[]>(
    partsData.length > 0 ? partsData : [
      { partCode: "", unit: "", materialType: "" },
      { partCode: "", unit: "", materialType: "" },
      { partCode: "", unit: "", materialType: "" },
      { partCode: "", unit: "", materialType: "" },
      { partCode: "", unit: "", materialType: "" }
    ]
  );

  const form = useForm<QualityFormData>({
    resolver: zodResolver(qualityFormSchema),
    defaultValues: {
      qualityExecutionDate: initialData?.qualityExecutionDate || "",
      qualityManagerApproval: initialData?.qualityManagerApproval || "",
    },
  });

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

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

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

  const addPartRow = () => {
    if (!canEdit) return;
    setParts([...parts, { partCode: "", unit: "", materialType: "" }]);
  };

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

  return (
    <Card className="w-full">
      <CardHeader className="bg-purple-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="qualityExecutionDate"
                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={addPartRow}
                    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((item, index) => (
                    <TableRow key={index}>
                      <TableCell>
                        <Input
                          value={item.partCode}
                          onChange={(e) => updatePart(index, 'partCode', e.target.value)}
                          placeholder="کد قطعه"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.unit}
                          onChange={(e) => updatePart(index, 'unit', e.target.value)}
                          placeholder="واحد"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          value={item.materialType}
                          onChange={(e) => updatePart(index, 'materialType', e.target.value)}
                          placeholder="نوع کالای مصرفی"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      {canEdit && (
                        <TableCell>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => removePartRow(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 Section - Manager/Deputy Only */}
            <div className="flex justify-center">
              <Card className="bg-green-50 w-full max-w-md">
                <CardHeader className="pb-3">
                  <CardTitle className="text-center text-sm">تایید مدیر/جانشین</CardTitle>
                </CardHeader>
                <CardContent>
                  <DigitalSignature
                    title="تایید مدیر/جانشین"
                    signedBy={initialData?.qualityManagerApproval}
                    signedAt={(initialData as any)?.qualityManagerApprovalDate}
                    signatureImageUrl={(initialData as any)?.qualityManagerApprovalImageUrl}
                    onSign={(data) => applySignatureMutation.mutate({ fieldName: "qualityManagerApproval" })}
                    signatureType="manager"
                    isEditable={canEdit}
                    currentApprovalText={initialData?.qualityManagerApproval}
                  />
                </CardContent>
              </Card>
            </div>

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

                <FormDelegation
                  formId={formId || ""}
                  currentDepartment="quality"
                  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>
  );
}