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 FinancialCodeRow {
  code: string;
}

interface FinancialFormData {
  financialExecutionDate: string;
  financialExpertApproval: string;
}

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

interface FinancialFormProps {
  initialData?: Partial<FinancialFormData>;
  codeData?: FinancialCodeRow[];
  onSave: (data: FinancialFormData, codes: FinancialCodeRow[]) => void;
  onSubmit: (data: FinancialFormData, codes: FinancialCodeRow[]) => void;
  isLoading?: boolean;
  canEdit?: boolean;
  formId?: string;
  onBeforeDelegate?: () => Promise<void>;
}

export default function FinancialForm({
  initialData,
  codeData = [],
  onSave,
  onSubmit,
  isLoading = false,
  canEdit = true,
  formId
}: FinancialFormProps) {
  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 [codes, setCodes] = useState<FinancialCodeRow[]>(
    codeData.length > 0 ? codeData : [
      { code: "" },
      { code: "" },
      { code: "" },
      { code: "" },
      { code: "" }
    ]
  );

  const form = useForm<FinancialFormData>({
    resolver: zodResolver(financialFormSchema),
    defaultValues: {
      financialExecutionDate: initialData?.financialExecutionDate || "",
      financialExpertApproval: initialData?.financialExpertApproval || "",
    },
  });

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

  const handleSubmit = (data: FinancialFormData) => {
    onSubmit(data, codes);
  };

  const updateCode = (index: number, value: string) => {
    if (!canEdit) return;
    const newCodes = [...codes];
    newCodes[index] = { code: value };
    setCodes(newCodes);
  };

  const addCodeRow = () => {
    if (!canEdit) return;
    setCodes([...codes, { code: "" }]);
  };

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

  return (
    <Card className="w-full">
      <CardHeader className="bg-green-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="financialExecutionDate"
                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 />

            {/* Code 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={addCodeRow}
                    className="flex items-center gap-2"
                  >
                    <Plus className="h-4 w-4" />
                    افزودن ردیف
                  </Button>
                )}
              </div>

              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="text-center">ثبت کد</TableHead>
                    {canEdit && <TableHead className="text-center">عملیات</TableHead>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {codes.map((item, index) => (
                    <TableRow key={index}>
                      <TableCell>
                        <Input
                          value={item.code}
                          onChange={(e) => updateCode(index, e.target.value)}
                          placeholder="ثبت کد"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      {canEdit && (
                        <TableCell>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => removeCodeRow(index)}
                            disabled={codes.length <= 1}
                            className="h-8 w-8 p-0"
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>

            <Separator />

            {/* Expert Approval Section */}
            <div className="space-y-4">
              <Card className="bg-orange-50">
                <CardHeader className="pb-3">
                  <CardTitle className="text-center text-sm">تایید کارشناس/سرپرست</CardTitle>
                </CardHeader>
                <CardContent>
                  <DigitalSignature
                    title="تایید کارشناس/سرپرست"
                    signedBy={initialData?.financialExpertApproval}
                    signedAt={(initialData as any)?.financialExpertApprovalDate}
                    signatureImageUrl={(initialData as any)?.financialExpertApprovalImageUrl}
                    onSign={(data) => applySignatureMutation.mutate({ fieldName: "financialExpertApproval" })}
                    signatureType="expert"
                    isEditable={canEdit}
                    currentApprovalText={initialData?.financialExpertApproval}
                  />
                </CardContent>
              </Card>
            </div>

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

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