"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { normalizeDate } from "@/utils";

import {
  Form,
  FormSection,
  FormField,
  FormLabel,
  FormInput,
  FormDatePicker,
  FormFileInput,
} from "@/components/ui/form";

import { StatutoryApprovalData } from "@/types";
import {
  StatutoryApprovalFormValues,
  statutoryApprovalSchema,
} from "@/schema/statutoryApproval";
import Modal from "@/components/ui/modal/Modal";
import ModalHeader from "@/components/ui/modal/ModalHeader";
import ModalFooter from "@/components/ui/modal/ModalFooter";
import ModalBody from "@/components/ui/modal/ModalBody";
import { showSuccess } from "@/components/ui/Toast";
import { FormFileDropzone } from "@/components/ui/form/FormFileDropzone";

export const EMPTY_STATUTORY_APPROVAL: StatutoryApprovalData = {
  approvalName: "",
  licenseNumber: "",
  issuedBy: "",
  issueDate: "",
  expiryDate: "",
  iecCode: "",
  pfNumber: "",
  esicNumber: "",
  licenseDocument: "",
  iecDocument: "",
  pfDocument: "",
  esicDocument: "",
};

interface Props {
  onSave: (data: StatutoryApprovalData) => Promise<void>;
  onClose: () => void;
}

export default function StatutoryApproval({ onSave, onClose }: Props) {
  const [globalError, setGlobalError] = useState<string>("");
  const [saving, setSaving] = useState(false);

  const form = useForm<StatutoryApprovalFormValues>({
    resolver: zodResolver(statutoryApprovalSchema),
    defaultValues: {
      ...EMPTY_STATUTORY_APPROVAL,
      issueDate: normalizeDate(EMPTY_STATUTORY_APPROVAL.issueDate) || "",
      expiryDate: normalizeDate(EMPTY_STATUTORY_APPROVAL.expiryDate) || "",
    },
  });

  const expiryDateValue = form.watch("expiryDate");
  const status = expiryDateValue
    ? (() => {
        const expiry = new Date(expiryDateValue);
        const today = new Date();
        const daysToExpiry = Math.ceil(
          (expiry.getTime() - today.getTime()) / (1000 * 60 * 60 * 24),
        );

        if (daysToExpiry < 0) return "Expired";
        if (daysToExpiry <= 30) return "Expiring Soon";
        return "Valid";
      })()
    : "";

  async function onSubmit(data: StatutoryApprovalFormValues) {
    setSaving(true);
    setGlobalError("");
    try {
      await onSave(data as StatutoryApprovalData);
      showSuccess("Statutory Approval added successfully");
      form.reset();
    } catch (err: unknown) {
      setGlobalError(err instanceof Error ? err.message : "Failed to save.");
    } finally {
      setSaving(false);
      onClose();
    }
  }

  return (
    <Modal maxWidth="max-w-5xl" onClose={onClose}>
      <ModalHeader
        title={"Add Statutory Approval"}
        subtitle=""
        onClose={onClose}
      />
      <ModalBody>
        <Form form={form} onSubmit={onSubmit} className="space-y-7">
          <FormSection title="Approval Details">
            <FormField colSpan={2}>
              <FormLabel required>Approval / License Name</FormLabel>
              <FormInput
                name="approvalName"
                placeholder="e.g. GST Registration, Factory License"
              />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>License Number</FormLabel>
              <FormInput name="licenseNumber" placeholder="L123456789" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>Issued By</FormLabel>
              <FormInput
                name="issuedBy"
                placeholder="e.g. Goods and Services Tax Department"
              />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>Issue Date</FormLabel>
              <FormDatePicker
                name="issueDate"
                placeholder="Select issue date"
              />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>Expiry Date</FormLabel>
              <FormDatePicker
                name="expiryDate"
                placeholder="Select expiry date"
              />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel>Status</FormLabel>
              <FormInput
                name="status"
                placeholder="Status"
                disabled
                value={status}
                className={
                  status === "Expired"
                    ? "text-red-600"
                    : status === "Expiring Soon"
                      ? "text-orange-600"
                      : "text-green-600"
                }
              />
            </FormField>

            <FormField colSpan={1}>
              {/* <FormLabel></FormLabel> */}
              <FormFileDropzone
                name="incorporationDoc"
                label="License Document(s)"
                accept=".pdf"
                maxSize={50}
              />
            </FormField>
          </FormSection>

          <FormSection title="Other Registrations">
            <FormField colSpan={1}>
              <FormLabel>IEC Code</FormLabel>
              <FormInput name="iecCode" placeholder="1234567890" />
            </FormField>

            <FormField colSpan={1}>
              <FormFileDropzone
                name="incorporationDoc"
                label="IEC Document"
                accept=".pdf"
                maxSize={50}
              />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>PF Number</FormLabel>
              <FormInput name="pfNumber" placeholder="PF Code" />
            </FormField>

            <FormField colSpan={1}>
              <FormFileDropzone
                name="incorporationDoc"
                label="PF Document"
                accept=".pdf"
                maxSize={50}
              />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>ESIC Number</FormLabel>
              <FormInput name="esicNumber" placeholder="ESIC Code" />
            </FormField>

            <FormField colSpan={1}>
              <FormFileDropzone
                name="esicDocument"
                label="ESIC Document"
                accept=".pdf"
                maxSize={50}
              />
            </FormField>
          </FormSection>
        </Form>
      </ModalBody>
      <ModalFooter
        globalError={globalError}
        saving={saving}
        onClose={onClose}
        onSubmit={form.handleSubmit(onSubmit)}
      />
    </Modal>
  );
}
