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 MonitoringRow {
  monitoringEntry: string;
}

import { planningFormSchema, type PlanningFormData } from "@/../../shared/schema";

interface PlanningFormProps {
  initialData?: Partial<PlanningFormData>;
  monitoringData?: MonitoringRow[];
  onSave: (data: PlanningFormData, monitoring: MonitoringRow[]) => void;
  onSubmit: (data: PlanningFormData, monitoring: MonitoringRow[]) => void;
  isLoading?: boolean;
  canEdit?: boolean;
  formId?: string;
  onBeforeDelegate?: () => Promise<void>;
}

export default function PlanningForm({
  initialData,
  monitoringData = [],
  onSave,
  onSubmit,
  isLoading = false,
  canEdit = true,
  formId,
  onBeforeDelegate
}: PlanningFormProps) {
  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 [monitoring, setMonitoring] = useState<MonitoringRow[]>(
    monitoringData.length > 0 ? monitoringData : [
      { monitoringEntry: "" },
      { monitoringEntry: "" },
      { monitoringEntry: "" },
      { monitoringEntry: "" },
      { monitoringEntry: "" }
    ]
  );

  const form = useForm<PlanningFormData>({
    resolver: zodResolver(planningFormSchema),
    defaultValues: {
      planningExecutionDate: initialData?.planningExecutionDate || "",
      planningManagerApproval: initialData?.planningManagerApproval || "",
      planningManagerApprovalImageUrl: initialData?.planningManagerApprovalImageUrl || "",
    },
  });

  const handleSave = async (data: PlanningFormData) => {
    if (!formId) return;
    
    try {
      // Prepare data with monitoring table
      const saveData = {
        ...data,
        planningMonitoringTable: monitoring
      };
      
      // 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, monitoring);
    } catch (error) {
      console.error("Error saving planning form:", error);
    }
  };

  const handleSubmit = (data: PlanningFormData) => {
    onSubmit(data, monitoring);
  };

  const updateMonitoring = (index: number, value: string) => {
    if (!canEdit) return;
    const newMonitoring = [...monitoring];
    newMonitoring[index] = { monitoringEntry: value };
    setMonitoring(newMonitoring);
  };

  const addMonitoringRow = () => {
    if (!canEdit) return;
    setMonitoring([...monitoring, { monitoringEntry: "" }]);
  };

  const removeMonitoringRow = (index: number) => {
    if (!canEdit || monitoring.length <= 1) return;
    setMonitoring(monitoring.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">
            {/* Date Field */}
            <div className="space-y-4">
              <FormField
                control={form.control}
                name="planningExecutionDate"
                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 />

            {/* Monitoring 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={addMonitoringRow}
                    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>
                  {monitoring.map((item, index) => (
                    <TableRow key={index}>
                      <TableCell>
                        <Input
                          value={item.monitoringEntry}
                          onChange={(e) => updateMonitoring(index, e.target.value)}
                          placeholder="ثبت در فایل پایش"
                          disabled={!canEdit}
                          className="text-right"
                        />
                      </TableCell>
                      {canEdit && (
                        <TableCell>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => removeMonitoringRow(index)}
                            disabled={monitoring.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="space-y-4">
              <DigitalSignature
                title="تایید مدیر"
                signedBy={initialData?.planningManagerApproval ? "امضا شده" : undefined}
                signedAt={initialData?.planningManagerApproval ? new Date().toISOString() : undefined}
                signatureImageUrl={initialData?.planningManagerApprovalImageUrl || undefined}
                currentApprovalText={initialData?.planningManagerApproval || undefined}
                onSign={async (signatureData) => {
                  await applySignatureMutation.mutateAsync({ fieldName: "planningManagerApproval" });
                }}
                required={true}
                isEditable={canEdit && !!formId}
                signatureType="manager"
              />
            </div>

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

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