"use client";

import { useCallback, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { X, AlertCircle } from "lucide-react";
import { Location as LocationData } from "@/types";
import { locationSchema, LocationFormValues } from "@/schema/location";

import {
  Form,
  FormSection,
  FormField,
  FormLabel,
  FormInput,
  FormSelect,
  FormTextarea,
  FormDatePicker,
  FormFileInput,
} from "@/components/ui/form";
import ModalFooter from "@/components/ui/modal/ModalFooter";
import ModalBody from "@/components/ui/modal/ModalBody";
import ModalHeader from "@/components/ui/modal/ModalHeader";
import Modal from "@/components/ui/modal/Modal";
import { FormFileDropzone } from "@/components/ui/form/FormFileDropzone";
import { useStateContext } from "@/context/StateContext";
import { useParams } from "next/navigation";
import locationService from "@/services/location.service";
import { showError, showSuccess } from "@/components/ui/Toast";

export const EMPTY_LOCATION: LocationData = {
  id: "",
  name: "",
  locationType: "Office",
  address: "",
  leaseStartDate: "",
  leaseEndDate: "",
  monthlyRent: 0,
  securityDeposit: 0,
  document: "",
};

const LOCATION_TYPES = ["Office", "Plant", "Warehouse"];

interface Props {
  initial?: LocationData;
  onClose: () => void;
  title?: string;
}

export default function LocationForm({
  initial = EMPTY_LOCATION,
  onClose,
  title = "Add Location",
}: Props) {
  const [globalError, setGlobalError] = useState<string>("");
  const { recordID, setRefresh, refresh } = useStateContext();
  const clientId = useParams().clientId as string;

  const form = useForm<LocationFormValues>({
    resolver: zodResolver(locationSchema),
    defaultValues: initial,
  });

  const fetchEditRecord = useCallback(async (id: string) => {
    const res = await locationService.getLocation(clientId, id);
    return res.data.data;
  }, []);

  const setFormData = useCallback((data: any) => {
    const str = (v: any) => v ?? ''
    form.reset({
      name: str(data.name),
      locationType: str(data.locationType),
      address: str(data.address),
      leaseStartDate: str(data.leaseStartDate),
      leaseEndDate: str(data.leaseEndDate),
      monthlyRent: str(data.monthlyRent),
      securityDeposit: str(data.securityDeposit),
      document: str(data.document),
    })
  }, [form.reset])


  useEffect(() => {
    if (recordID) {
      fetchEditRecord(recordID)
        .then(setFormData)
        .catch(err => {
          console.error(err);
          showError("Failed to load director");
        });
    } else {
      form.reset({ ...EMPTY_LOCATION });
    }
  }, [recordID, fetchEditRecord, setFormData, form]);

  async function onSubmit(data: LocationFormValues) {

    setGlobalError("");
    try {
      const formData = new FormData()
      Object.entries(data).forEach(([key, value]) => {
        if (value === undefined || value === null) return

        if (value instanceof FileList && value.length > 0) {
          formData.append(key, value[0])
        } else if (typeof value === 'string' && value) {
          formData.append(key, value)
        }

      })
      if (recordID) {
        await locationService.updateLocation(clientId, recordID, formData)
        showSuccess('Location updated successfully')

      } else {
        await locationService.createLocation(clientId, formData)
        showSuccess('Location added successfully')
      }
      onClose();
    } catch (err: unknown) {
      setGlobalError(err instanceof Error ? err.message : "Failed to save.");
    }
    finally {
      setRefresh(!refresh);
    }
  }

  return (
    <Modal
      onClose={onClose}
      isOpen={true}
    >
      <ModalHeader
        title={title}
        subtitle=""
        onClose={onClose}
      />
      <ModalBody>
        <Form form={form} onSubmit={onSubmit} className="space-y-7">
          <FormSection title="Location Details">
            <FormField colSpan={2}>
              <FormLabel required>Location Name</FormLabel>
              <FormInput
                name="name"
                placeholder="Mumbai HO"
              />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel required>Location Type</FormLabel>
              <FormSelect
                name="locationType"
                options={LOCATION_TYPES}
              />
            </FormField>

            <FormField colSpan={2}>
              <FormLabel required>Address</FormLabel>
              <FormTextarea
                name="address"
                rows={3}
                placeholder="Enter complete address"
              />
            </FormField>
          </FormSection>

          <FormSection title="Lease Details">
            <FormField colSpan={1}>
              <FormLabel>Lease Start Date</FormLabel>
              <FormDatePicker name="leaseStartDate" placeholder="Select date" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel>Lease End Date</FormLabel>
              <FormDatePicker name="leaseEndDate" placeholder="Select date" />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel>Monthly Rent (₹)</FormLabel>
              <FormInput
                name="monthlyRent"
                type="number"
                placeholder="50000"
              />
            </FormField>

            <FormField colSpan={1}>
              <FormLabel>Security Deposit (₹)</FormLabel>
              <FormInput
                name="securityDeposit"
                type="number"
                placeholder="200000"
              />
            </FormField>
          </FormSection>

          <FormSection title="Documents">
            <FormField colSpan={2}>
              {/* <FormLabel>t</FormLabel> */}
              {initial?.document && (
                <div className="mb-2 p-2 bg-blue-50 border border-blue-200 rounded-lg">
                  <p className="text-xs text-blue-700">
                    Current: <span className="font-semibold">{initial.document}</span>
                  </p>
                </div>
              )}
              <FormFileInput
                name="document"
                accept=".pdf,.doc,.docx"
                placeholder="Upload lease agreement"
              />
              {/* <FormFileDropzone
                name="LeaseDocument"
                accept=".pdf,.doc,.docx"
                label="Lease Document"

                placeholder="Upload lease agreement"
              />
              <p className="text-[10px] text-gray-500 mt-1">Leave empty to keep existing document</p> */}
            </FormField>
          </FormSection>
        </Form>
      </ModalBody>
      <ModalFooter
        globalError={globalError}
        saving={form.formState.isSubmitting}
        onClose={onClose}
        onSubmit={form.handleSubmit(onSubmit)}
      />
    </Modal>
  );
}
