"use client";

import type { ReactNode } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { PhoneInput } from "@/components/ui/phone-input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { User } from "lucide-react";

type Props = {
  onCancel?: () => void;
  onNext?: () => void;
};

const cancelClass =
  "rounded-md bg-[#EF6C00] px-8 text-white hover:bg-[#EF6C00]/90 focus-visible:ring-[#EF6C00]";
const primaryClass =
  "rounded-md bg-[#074473] px-8 text-white hover:bg-[#074473]/90 focus-visible:ring-[#074473]";

const controlClass = cn(
  "h-10 w-full rounded-lg border border-[#E0E2E9] bg-[#F8F9FC] text-sm text-[#16151C] shadow-none",
  "placeholder:text-[#ABAFB1] focus-visible:border-[#074473] focus-visible:bg-white focus-visible:ring-2 focus-visible:ring-[#074473]/20 focus-visible:ring-offset-0",
);

const textareaClass = cn(
  "min-h-[168px] w-full resize-y rounded-lg border border-[#E0E2E9] bg-[#F8F9FC] text-sm text-[#16151C] shadow-none",
  "placeholder:text-[#ABAFB1] focus-visible:border-[#074473] focus-visible:bg-white focus-visible:ring-2 focus-visible:ring-[#074473]/20 focus-visible:ring-offset-0",
);

const labelClass = "text-xs font-medium text-[#545D69]";

function Field({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="space-y-2">
      <Label className={labelClass}>{label}</Label>
      {children}
    </div>
  );
}

const BlockAddPersonalInformation = ({ onCancel, onNext }: Props) => {
  const fileRef = useRef<HTMLInputElement>(null);
  const [photoPreview, setPhotoPreview] = useState<string | null>(null);
  const [phone, setPhone] = useState("");

  const onPhotoChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const url = URL.createObjectURL(file);
    setPhotoPreview((prev) => {
      if (prev) URL.revokeObjectURL(prev);
      return url;
    });
  }, []);

  useEffect(() => {
    return () => {
      if (photoPreview) URL.revokeObjectURL(photoPreview);
    };
  }, [photoPreview]);

  return (
    <div className="flex flex-col gap-8 lg:flex-row lg:items-start lg:gap-10">
      <aside className="flex w-full flex-col items-center border-b border-[#EBEEF2] pb-8 lg:w-[220px] lg:shrink-0 lg:border-b-0 lg:border-r lg:pb-0 lg:pr-8">
        <Label className={cn(labelClass, "self-start lg:self-center")}>Profile Picture</Label>
        <button
          type="button"
          onClick={() => fileRef.current?.click()}
          className={cn(
            "relative mt-3 flex size-[120px] cursor-pointer items-center justify-center overflow-hidden rounded-full border-2 border-dashed border-[#CFD3D4] bg-[#F8F9FC] transition-colors hover:border-[#074473]/40 hover:bg-[#F0F4F8]",
          )}
          aria-label="Upload profile picture"
        >
          {photoPreview ? (
            <img src={photoPreview} alt="" className="size-full object-cover" />
          ) : (
            <User className="size-12 text-[#C2C7CE]" strokeWidth={1.25} aria-hidden />
          )}
        </button>
        <input
          ref={fileRef}
          type="file"
          accept="image/png,image/jpeg,image/webp"
          className="sr-only"
          onChange={onPhotoChange}
        />
        <Button
          type="button"
          variant="outline"
          className="mt-4 h-9 rounded-lg border-[#E0E2E9] bg-white text-sm font-medium text-[#383E49] hover:bg-[#F8F9FC]"
          onClick={() => fileRef.current?.click()}
        >
          Upload Image
        </Button>
        <p className="mt-2 max-w-[200px] text-center text-xs leading-snug text-[#858C94]">
          Recommended 400×400px. PNG, JPG or WEBP up to 5MB.
        </p>
      </aside>

      <div className="min-w-0 flex-1 space-y-6">
        <p className="text-sm leading-relaxed text-[#858C94]">
          Enter details exactly as they appear on the employee&apos;s official identification.
        </p>

        <div className="grid w-full max-w-full gap-5 md:grid-cols-2">
          <Field label="First Name">
            <Input className={controlClass} placeholder="David" autoComplete="given-name" />
          </Field>
          <Field label="Last Name">
            <Input className={controlClass} placeholder="Jordan" autoComplete="family-name" />
          </Field>
          <Field label="Phone Number">
            <PhoneInput
              value={phone}
              onChange={setPhone}
              inputClassName={controlClass}
              placeholder="3XXXXXXXXX"
            />
          </Field>
          <Field label="Email">
            <Input
              className={controlClass}
              type="email"
              placeholder="any@gmail.com"
              autoComplete="email"
            />
          </Field>
          <Field label="Date of Birth">
            <Input className={cn(controlClass, "text-[#16151C]")} type="date" />
          </Field>
          <Field label="Marital Status">
            <Select>
              <SelectTrigger className={controlClass}>
                <SelectValue placeholder="Select status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="single">Single</SelectItem>
                <SelectItem value="married">Married</SelectItem>
                <SelectItem value="divorced">Divorced</SelectItem>
                <SelectItem value="widowed">Widowed</SelectItem>
              </SelectContent>
            </Select>
          </Field>
          <Field label="Gender">
            <Select>
              <SelectTrigger className={controlClass}>
                <SelectValue placeholder="Select gender" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="male">Male</SelectItem>
                <SelectItem value="female">Female</SelectItem>
                <SelectItem value="other">Other</SelectItem>
                <SelectItem value="prefer-not">Prefer not to say</SelectItem>
              </SelectContent>
            </Select>
          </Field>
          <Field label="Nationality">
            <Input className={controlClass} placeholder="Saudi Arabia" />
          </Field>
          <Field label="City">
            <Input className={controlClass} placeholder="California" autoComplete="address-level2" />
          </Field>
          <Field label="State">
            <Input className={controlClass} placeholder="California" autoComplete="address-level1" />
          </Field>
        </div>

        <div className="grid gap-5 md:grid-cols-[minmax(0,240px)_1fr] md:items-start">
          <div className="flex flex-col gap-5">
            <Field label="Country">
              <Input className={controlClass} placeholder="USA" autoComplete="country-name" />
            </Field>
            <Field label="Zip Code">
              <Input className={controlClass} placeholder="000000" autoComplete="postal-code" />
            </Field>
          </div>
          <div className="space-y-2">
            <Label className={labelClass}>Address</Label>
            <Textarea
              className={textareaClass}
              rows={6}
              placeholder="Street, building, floor, apartment…"
              autoComplete="street-address"
            />
          </div>
        </div>

        <div className="flex flex-col justify-end gap-3 pt-2 sm:flex-row sm:justify-end sm:gap-4">
          <Button type="button" variant="secondary" className={cancelClass} onClick={onCancel}>
            Cancel
          </Button>
          <Button type="button" className={primaryClass} onClick={onNext}>
            Next
          </Button>
        </div>
      </div>
    </div>
  );
};

export default BlockAddPersonalInformation;
