import React, { useRef, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate, useParams } from 'react-router-dom';
import { __ } from '@/lib/i18n';
import { CustomersApi, type CustomerFormData } from '@/lib/api/customers';
import { showErrorToast, showSuccessToast, getPageLoadErrorMessage } from '@/lib/errorHandling';
import { useFABConfig } from '@/hooks/useFABConfig';
import { usePageHeader } from '@/contexts/PageHeaderContext';
import { CustomerForm } from './CustomerForm';
import { Button } from '@/components/ui/button';
import { ErrorCard } from '@/components/ErrorCard';
import { Skeleton } from '@/components/ui/skeleton';

export default function CustomerEdit() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const formRef = useRef<HTMLFormElement>(null);
  const { setPageHeader, clearPageHeader } = usePageHeader();
  
  // Hide FAB on edit customer page
  useFABConfig('none');
  
  // Fetch customer
  const customerQuery = useQuery({
    queryKey: ['customers', id],
    queryFn: () => CustomersApi.get(Number(id)),
    enabled: !!id,
  });
  
  // Update mutation
  const updateMutation = useMutation({
    mutationFn: (data: CustomerFormData) => CustomersApi.update(Number(id), data),
    onSuccess: (customer) => {
      showSuccessToast(__('Customer updated successfully'));
      queryClient.invalidateQueries({ queryKey: ['customers'] });
      queryClient.invalidateQueries({ queryKey: ['customers', id] });
      navigate('/customers');
    },
    onError: (error: any) => {
      showErrorToast(error);
    },
  });
  
  const handleSubmit = async (data: CustomerFormData) => {
    await updateMutation.mutateAsync(data);
  };
  
  // Smart back handler: go back in history if available, otherwise fallback to /customers
  const handleBack = () => {
    if (window.history.state?.idx > 0) {
      navigate(-1); // Go back in history
    } else {
      navigate('/customers'); // Fallback to customers index
    }
  };

  // Set page header with back button and save button
  useEffect(() => {
    const actions = (
      <div className="flex gap-2">
        <Button size="sm" variant="ghost" onClick={handleBack}>
          {__('Back')}
        </Button>
        <Button 
          size="sm" 
          onClick={() => formRef.current?.requestSubmit()}
          disabled={updateMutation.isPending || customerQuery.isLoading}
        >
          {updateMutation.isPending ? __('Saving...') : __('Save Changes')}
        </Button>
      </div>
    );
    setPageHeader(__('Edit Customer'), actions);
    return () => clearPageHeader();
  }, [updateMutation.isPending, customerQuery.isLoading, setPageHeader, clearPageHeader, navigate]);
  
  // Loading state
  if (customerQuery.isLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-12 w-full" />
        <Skeleton className="h-64 w-full" />
        <Skeleton className="h-32 w-full" />
      </div>
    );
  }
  
  // Error state
  if (customerQuery.isError) {
    return (
      <ErrorCard
        title={__('Failed to load customer')}
        message={getPageLoadErrorMessage(customerQuery.error)}
        onRetry={() => customerQuery.refetch()}
      />
    );
  }
  
  const customer = customerQuery.data;
  
  return (
    <div>
      <CustomerForm
        mode="edit"
        initial={customer}
        onSubmit={handleSubmit}
        formRef={formRef}
        hideSubmitButton={true}
      />
    </div>
  );
}
