"use client";

import React, { useState, useEffect } from "react";
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  CardFooter,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { errorAutoClose, loading, successAutoClose } from "@/lib/swal";
import { close } from "@/config/swal";
import Image from "next/image";

// ✅ Zod Schema Validasi
const companySchema = z.object({
  companyName: z.string().trim().min(1, "Nama perusahaan wajib diisi"),
  address: z.string().trim().min(1, "Alamat perusahaan wajib diisi"),
  phone: z
    .string()
    .regex(/^[0-9+\-\s]+$/, "Nomor telepon tidak valid")
    .min(6, "Nomor telepon minimal 6 karakter"),
  website: z
    .string()
    .url("Masukkan URL website yang valid")
    .optional()
    .or(z.literal("")),
  description: z.string().trim().optional(),
  isActive: z.boolean().default(true),
  logo: z.any().optional(),
});

type CompanySchema = z.infer<typeof companySchema>;

interface TenantCompanyUpdateFormProps {
  id: number;
  initialData?: any;
  onSuccess?: () => void;
  onCancel?: () => void;
}

export default function TenantCompanyUpdateForm({
  id,
  initialData,
  onSuccess,
  onCancel,
}: TenantCompanyUpdateFormProps) {
  const MySwal = withReactContent(Swal);
  const [previewLogo, setPreviewLogo] = useState<string | null>(null);
  const [loadingData, setLoadingData] = useState(false);

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
    watch,
  } = useForm<CompanySchema>({
    resolver: zodResolver(companySchema),
    defaultValues: {
      companyName: "",
      address: "",
      phone: "",
      website: "",
      description: "",
      isActive: true,
    },
  });

  // ✅ Load data awal dari server
  useEffect(() => {
    async function fetchCompanyData() {
      setLoadingData(true);
      try {
        // TODO: ganti dengan service API kamu (misalnya getTenantCompanyDetail)
        const response = initialData; // simulasi
        if (response) {
          setValue("companyName", response.companyName || "");
          setValue("address", response.address || "");
          setValue("phone", response.phone || "");
          setValue("website", response.website || "");
          setValue("description", response.description || "");
          setValue("isActive", response.isActive ?? true);
          setPreviewLogo(response.logoUrl || null);
        }
      } catch (err) {
        console.error("❌ Gagal memuat data perusahaan:", err);
      } finally {
        setLoadingData(false);
      }
    }

    fetchCompanyData();
  }, [initialData, setValue]);

  // ✅ Fungsi Upload Logo
  const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (!file.type.startsWith("image/")) {
      MySwal.fire({
        icon: "error",
        title: "Format tidak valid",
        text: "File harus berupa gambar (jpg, png, webp, dll)",
      });
      return;
    }

    setValue("logo", file);
    setPreviewLogo(URL.createObjectURL(file));
  };

  // ✅ Submit Form
  const onSubmit = async (data: CompanySchema) => {
    try {
      loading();

      const formData = new FormData();
      formData.append("companyName", data.companyName);
      formData.append("address", data.address);
      formData.append("phone", data.phone);
      formData.append("website", data.website || "");
      formData.append("description", data.description || "");
      formData.append("isActive", data.isActive ? "true" : "false");
      if (data.logo) formData.append("logo", data.logo);

      console.log("📦 Payload:", Object.fromEntries(formData.entries()));

      // TODO: Ganti dengan service API kamu → misalnya updateTenantCompany(formData)
      // const response = await updateTenantCompany(id, formData);
      await new Promise((resolve) => setTimeout(resolve, 1000)); // simulate
      close();

      successAutoClose("Data perusahaan berhasil diperbarui.");

      setTimeout(() => {
        if (onSuccess) onSuccess();
      }, 2000);
    } catch (err) {
      close();
      console.error("❌ Gagal update perusahaan:", err);
      errorAutoClose("Terjadi kesalahan saat memperbarui data perusahaan.");
    }
  };

  if (loadingData) {
    return (
      <Card className="p-6 w-full lg:w-2/3">
        <div className="flex items-center justify-center py-8">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto mb-4"></div>
            <p>Memuat data perusahaan...</p>
          </div>
        </div>
      </Card>
    );
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Card className="p-6 w-full lg:w-2/3">
        <CardHeader>
          <CardTitle className="text-lg font-semibold">
            Update Informasi Perusahaan
          </CardTitle>
        </CardHeader>

        <CardContent className="space-y-4">
          {/* Logo Upload */}
          <div className="space-y-2">
            <Label>Logo Perusahaan</Label>
            <div className="flex items-center gap-4">
              <Input
                type="file"
                accept="image/*"
                onChange={handleLogoChange}
                className="max-w-xs"
              />
              {previewLogo && (
                <div className="relative w-20 h-20 rounded-lg overflow-hidden border">
                  <Image
                    src={previewLogo}
                    alt="Company Logo"
                    fill
                    className="object-cover"
                  />
                </div>
              )}
            </div>
          </div>

          {/* Nama Perusahaan */}
          <div>
            <Label>Nama Perusahaan</Label>
            <Controller
              control={control}
              name="companyName"
              render={({ field }) => (
                <Input {...field} placeholder="Masukkan nama perusahaan" />
              )}
            />
            {errors.companyName && (
              <p className="text-red-500 text-sm">
                {errors.companyName.message}
              </p>
            )}
          </div>

          {/* Alamat */}
          <div>
            <Label>Alamat</Label>
            <Controller
              control={control}
              name="address"
              render={({ field }) => (
                <Textarea {...field} placeholder="Masukkan alamat lengkap" />
              )}
            />
            {errors.address && (
              <p className="text-red-500 text-sm">{errors.address.message}</p>
            )}
          </div>

          {/* Nomor Telepon */}
          <div>
            <Label>Nomor Telepon</Label>
            <Controller
              control={control}
              name="phone"
              render={({ field }) => (
                <Input {...field} placeholder="Masukkan nomor telepon" />
              )}
            />
            {errors.phone && (
              <p className="text-red-500 text-sm">{errors.phone.message}</p>
            )}
          </div>

          {/* Website */}
          <div>
            <Label>Website Resmi</Label>
            <Controller
              control={control}
              name="website"
              render={({ field }) => (
                <Input {...field} placeholder="https://example.com" />
              )}
            />
            {errors.website && (
              <p className="text-red-500 text-sm">{errors.website.message}</p>
            )}
          </div>

          {/* Deskripsi Perusahaan */}
          <div>
            <Label>Biodata / Deskripsi Perusahaan</Label>
            <Controller
              control={control}
              name="description"
              render={({ field }) => (
                <Textarea
                  {...field}
                  placeholder="Ceritakan tentang perusahaan Anda..."
                />
              )}
            />
          </div>

          {/* Status Aktif */}
          <div className="flex items-center space-x-2">
            <Controller
              control={control}
              name="isActive"
              render={({ field }) => (
                <Checkbox
                  checked={field.value}
                  onCheckedChange={field.onChange}
                />
              )}
            />
            <Label>Aktif</Label>
          </div>
        </CardContent>

        <CardFooter className="flex justify-end gap-3">
          <Button type="submit">Update</Button>
          <Button type="button" variant="outline" onClick={() => onCancel?.()}>
            Cancel
          </Button>
        </CardFooter>
      </Card>
    </form>
  );
}
