"use client";

import { useState, useEffect, useCallback } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { createClient } from "@/lib/supabase/client";
import { jsonToPostgresPoint } from "@/lib/location-utils";
import { csrfFetch } from "@/lib/csrf-client";
import { generateBio } from "../utils/bio";
import { generateDisplayName } from "@/lib/display-names";
import type { WorkerData } from "../types";

const STORAGE_KEY = "rateright-worker-signup-progress";

type SavedProgress = {
  selectedTrades: string[];
  experience: number | null;
  suburb: string;
  availability: WorkerData["availability"] | null;
  certifications: string[];
  phone: string;
  lastStep: string;
  savedAt: string;
};

function loadProgress(): Partial<SavedProgress> | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const data = JSON.parse(raw) as SavedProgress;
    // Expire after 7 days
    const savedAt = new Date(data.savedAt).getTime();
    if (Date.now() - savedAt > 7 * 24 * 60 * 60 * 1000) {
      localStorage.removeItem(STORAGE_KEY);
      return null;
    }
    return data;
  } catch {
    return null;
  }
}

function clearProgress() {
  try { localStorage.removeItem(STORAGE_KEY); } catch { /* noop */ }
}

export function useWorkerProfile() {
  const saved = typeof window !== "undefined" ? loadProgress() : null;

  const [selectedTrades, setSelectedTrades] = useState<string[]>(saved?.selectedTrades || []);
  const [experience, setExperience] = useState<number | null>(saved?.experience ?? null);
  const [suburb, setSuburb] = useState(saved?.suburb || "");
  const [availability, setAvailability] = useState<WorkerData["availability"] | null>(saved?.availability ?? null);
  const [certifications, setCertifications] = useState<string[]>(saved?.certifications || []);
  const [phone, setPhone] = useState(saved?.phone || "");
  const [saving, setSaving] = useState(false);
  const [isQuickPath, setIsQuickPath] = useState(false);
  const [resumedFrom, setResumedFrom] = useState<string | null>(saved?.lastStep || null);

  // Auto-save progress on every field change
  const saveProgress = useCallback((lastStep?: string) => {
    try {
      const data: SavedProgress = {
        selectedTrades,
        experience,
        suburb,
        availability,
        certifications,
        phone,
        lastStep: lastStep || "method",
        savedAt: new Date().toISOString(),
      };
      localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    } catch { /* localStorage may be unavailable */ }
  }, [selectedTrades, experience, suburb, availability, certifications, phone]);

  // Save whenever fields change
  useEffect(() => {
    if (selectedTrades.length > 0 || suburb || phone) {
      saveProgress();
    }
  }, [selectedTrades, experience, suburb, availability, certifications, phone, saveProgress]);

  const router = useRouter();
  const supabase = createClient();

  // Load existing profile data (e.g. phone from initial auth step) if not already set
  useEffect(() => {
    async function loadInitialProfile() {
      if (saved?.phone || phone) return;
      try {
        const { data: { user } } = await supabase.auth.getUser();
        if (!user) return;
        const { data: profile } = await supabase
          .from("profiles")
          .select("phone")
          .eq("id", user.id)
          .single();
        if (profile?.phone && !phone) {
          setPhone(profile.phone);
        }
      } catch (err) {
        // Silently fail, user can enter manually
      }
    }
    loadInitialProfile();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function toggleTrade(trade: string) {
    setSelectedTrades((prev) =>
      prev.includes(trade) ? prev.filter((t) => t !== trade) : [...prev, trade]
    );
  }

  function toggleCert(cert: string) {
    setCertifications((prev) =>
      prev.includes(cert) ? prev.filter((c) => c !== cert) : [...prev, cert]
    );
  }

  // Australian phone number validation
  const validateAustralianPhone = (phone: string): boolean => {
    // Remove all non-digit characters
    const digits = phone.replace(/\D/g, '');
    
    // Check for Australian mobile formats:
    // - 04xx xxx xxx (10 digits starting with 04)
    // - +614xxxxxxxx (11 digits starting with +614, remove + for validation)
    if (digits.length === 10 && digits.startsWith('04')) {
      return true;
    }
    if (digits.length === 11 && digits.startsWith('614')) {
      return true;
    }
    
    return false;
  };

  async function saveWorkerProfile() {
    if (!availability || experience === null) return;
    
    // Validate phone number if provided
    if (phone && !validateAustralianPhone(phone)) {
      toast.error("Please enter a valid Australian phone number (04xx xxx xxx or +614xxxxxxxx)");
      return;
    }
    
    setSaving(true);

    try {
      const {
        data: { user },
      } = await supabase.auth.getUser();
      if (!user) {
        toast.error("Not logged in. Please sign in again.");
        setSaving(false);
        return;
      }

      const workerData: WorkerData = {
        trades: selectedTrades,
        experience,
        suburb,
        availability,
        certifications,
        phone: phone || undefined,
      };

      const bio = generateBio(workerData);

      // Geocode the suburb to get lat/lng coordinates
      let location: string | null = null;
      if (suburb) {
        try {
          const geocodeRes = await csrfFetch("/api/geocode", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ suburb }),
          });

          if (geocodeRes.ok) {
            const geocodeData = await geocodeRes.json();
            if (geocodeData.location) {
              location = jsonToPostgresPoint(geocodeData.location);
            }
          }
        } catch (geoError) {
          // Continue without location - suburb text will still be saved
        }
      }

      // Use name from auth metadata (set during signup), fallback to email prefix
      const userName = user.user_metadata?.name || user.email?.split("@")[0] || "";

      const profileResult = await supabase.from("profiles").update({
        name: userName,
        display_name: userName || generateDisplayName(),
        suburb,
        location,
        phone: phone || null,
        onboarding_completed: true,
      }).eq("id", user.id);

      if (profileResult.error) {
        toast.error(`Profile update failed: ${profileResult.error.message}`);
        setSaving(false);
        return;
      }

      const workerResult = await supabase.from("worker_profiles").insert({
        profile_id: user.id,
        trades: selectedTrades,
        experience_years: experience,
        availability,
        certifications,
        bio,
        ai_extracted: {
          source: "typed_answers",
          created_at: new Date().toISOString(),
        },
      }).select();

      if (workerResult.error) {
        toast.error(`Worker profile creation failed: ${workerResult.error.message}`);
        setSaving(false);
        return;
      }

      clearProgress();
      router.push("/dashboard");
      router.refresh();
    } catch (error: any) {
      toast.error(`Something went wrong: ${error.message || "Unknown error"}`);
      setSaving(false);
    }
  }

  // Quick path: save with minimal info (trade + location + phone only)
  async function saveQuickProfile() {
    if (selectedTrades.length === 0 || !suburb) {
      toast.error("Please select at least one trade and your location.");
      return;
    }

    // Validate phone if provided
    if (phone && !validateAustralianPhone(phone)) {
      toast.error("Please enter a valid Australian phone number");
      return;
    }

    setSaving(true);

    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) {
        toast.error("Not logged in. Please sign in again.");
        setSaving(false);
        return;
      }

      const quickData: WorkerData = {
        trades: selectedTrades,
        experience: experience ?? 0,
        suburb,
        availability: availability || "flexible",
        certifications,
        phone: phone || undefined,
      };

      const bio = generateBio(quickData);

      let location: string | null = null;
      if (suburb) {
        try {
          const geocodeRes = await csrfFetch("/api/geocode", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ suburb }),
          });
          if (geocodeRes.ok) {
            const geocodeData = await geocodeRes.json();
            if (geocodeData.location) {
              location = jsonToPostgresPoint(geocodeData.location);
            }
          }
        } catch { /* continue without location */ }
      }

      const userName = user.user_metadata?.name || user.email?.split("@")[0] || "";

      const profileResult = await supabase.from("profiles").update({
        name: userName,
        display_name: userName || generateDisplayName(),
        suburb,
        location,
        phone: phone || null,
        onboarding_completed: true,
      }).eq("id", user.id);

      if (profileResult.error) {
        toast.error(`Profile update failed: ${profileResult.error.message}`);
        setSaving(false);
        return;
      }

      const workerResult = await supabase.from("worker_profiles").insert({
        profile_id: user.id,
        trades: selectedTrades,
        experience_years: quickData.experience,
        availability: quickData.availability,
        certifications,
        bio,
        ai_extracted: {
          source: "quick_signup",
          created_at: new Date().toISOString(),
        },
      }).select();

      if (workerResult.error) {
        toast.error(`Worker profile creation failed: ${workerResult.error.message}`);
        setSaving(false);
        return;
      }

      clearProgress();
      toast.success("Profile created! Complete your full profile to get more matches.");
      router.push("/dashboard");
      router.refresh();
    } catch (error: any) {
      toast.error(`Something went wrong: ${error.message || "Unknown error"}`);
      setSaving(false);
    }
  }

  const workerData: WorkerData | null =
    selectedTrades.length > 0 && experience !== null && suburb && availability
      ? { trades: selectedTrades, experience, suburb, availability, certifications }
      : null;

  return {
    selectedTrades,
    setSelectedTrades,
    experience,
    setExperience,
    suburb,
    setSuburb,
    availability,
    setAvailability,
    certifications,
    setCertifications,
    phone,
    setPhone,
    saving,
    toggleTrade,
    toggleCert,
    saveWorkerProfile,
    saveQuickProfile,
    workerData,
    isQuickPath,
    setIsQuickPath,
    resumedFrom,
    setResumedFrom,
    saveProgress,
  };
}