import React, { useState, useEffect } from 'react';
import { __ } from '@/lib/i18n';
import { VerticalTabForm, FormSection } from '@/components/VerticalTabForm';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { User, MapPin, Home } from 'lucide-react';
import type { Customer, CustomerFormData } from '@/lib/api/customers';

type Props = {
  mode: 'create' | 'edit';
  initial?: Customer | null;
  onSubmit: (data: CustomerFormData) => Promise<void> | void;
  className?: string;
  formRef?: React.RefObject<HTMLFormElement>;
  hideSubmitButton?: boolean;
};

export function CustomerForm({
  mode,
  initial,
  onSubmit,
  className,
  formRef,
  hideSubmitButton = false,
}: Props) {
  // Personal data
  const [email, setEmail] = useState(initial?.email || '');
  const [firstName, setFirstName] = useState(initial?.first_name || '');
  const [lastName, setLastName] = useState(initial?.last_name || '');
  const [username, setUsername] = useState(initial?.username || '');
  const [password, setPassword] = useState('');
  const [sendEmail, setSendEmail] = useState(mode === 'create');
  
  // Billing address
  const [billingCompany, setBillingCompany] = useState(initial?.billing?.company || '');
  const [billingAddress1, setBillingAddress1] = useState(initial?.billing?.address_1 || '');
  const [billingAddress2, setBillingAddress2] = useState(initial?.billing?.address_2 || '');
  const [billingCity, setBillingCity] = useState(initial?.billing?.city || '');
  const [billingState, setBillingState] = useState(initial?.billing?.state || '');
  const [billingPostcode, setBillingPostcode] = useState(initial?.billing?.postcode || '');
  const [billingCountry, setBillingCountry] = useState(initial?.billing?.country || '');
  const [billingPhone, setBillingPhone] = useState(initial?.billing?.phone || '');
  
  // Shipping address
  const [shippingCompany, setShippingCompany] = useState(initial?.shipping?.company || '');
  const [shippingAddress1, setShippingAddress1] = useState(initial?.shipping?.address_1 || '');
  const [shippingAddress2, setShippingAddress2] = useState(initial?.shipping?.address_2 || '');
  const [shippingCity, setShippingCity] = useState(initial?.shipping?.city || '');
  const [shippingState, setShippingState] = useState(initial?.shipping?.state || '');
  const [shippingPostcode, setShippingPostcode] = useState(initial?.shipping?.postcode || '');
  const [shippingCountry, setShippingCountry] = useState(initial?.shipping?.country || '');
  const [copyBilling, setCopyBilling] = useState(false);
  
  // Submitting state
  const [submitting, setSubmitting] = useState(false);
  
  // Copy billing to shipping
  useEffect(() => {
    if (copyBilling) {
      setShippingCompany(billingCompany);
      setShippingAddress1(billingAddress1);
      setShippingAddress2(billingAddress2);
      setShippingCity(billingCity);
      setShippingState(billingState);
      setShippingPostcode(billingPostcode);
      setShippingCountry(billingCountry);
    }
  }, [copyBilling, billingCompany, billingAddress1, billingAddress2, billingCity, billingState, billingPostcode, billingCountry]);
  
  // Handle submit
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const data: CustomerFormData = {
      email,
      first_name: firstName,
      last_name: lastName,
      billing: {
        first_name: firstName,
        last_name: lastName,
        company: billingCompany,
        address_1: billingAddress1,
        address_2: billingAddress2,
        city: billingCity,
        state: billingState,
        postcode: billingPostcode,
        country: billingCountry,
        phone: billingPhone,
      },
      shipping: {
        first_name: firstName,
        last_name: lastName,
        company: shippingCompany,
        address_1: shippingAddress1,
        address_2: shippingAddress2,
        city: shippingCity,
        state: shippingState,
        postcode: shippingPostcode,
        country: shippingCountry,
      },
    };
    
    // Add username and password for new customers
    if (mode === 'create') {
      if (username) data.username = username;
      if (password) data.password = password;
      data.send_email = sendEmail;
    } else if (password) {
      // Only include password if changing it
      data.password = password;
    }
    
    try {
      setSubmitting(true);
      await onSubmit(data);
    } finally {
      setSubmitting(false);
    }
  };
  
  // Define tabs
  const tabs = [
    { id: 'personal', label: __('Personal Data'), icon: <User className="w-4 h-4" /> },
    { id: 'billing', label: __('Billing Address'), icon: <MapPin className="w-4 h-4" /> },
    { id: 'shipping', label: __('Shipping Address'), icon: <Home className="w-4 h-4" /> },
  ];
  
  return (
    <form ref={formRef} onSubmit={handleSubmit} className={className}>
      <VerticalTabForm tabs={tabs}>
        {/* Personal Data */}
        <FormSection id="personal">
          <Card>
            <CardHeader>
              <CardTitle>{__('Personal Information')}</CardTitle>
              <CardDescription>
                {__('Basic customer information and account details')}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="first_name">{__('First Name')} *</Label>
                  <Input
                    id="first_name"
                    value={firstName}
                    onChange={(e) => setFirstName(e.target.value)}
                    required
                  />
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="last_name">{__('Last Name')} *</Label>
                  <Input
                    id="last_name"
                    value={lastName}
                    onChange={(e) => setLastName(e.target.value)}
                    required
                  />
                </div>
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="email">{__('Email')} *</Label>
                <Input
                  id="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
              </div>
              
              {mode === 'create' && (
                <div className="space-y-2">
                  <Label htmlFor="username">{__('Username')}</Label>
                  <Input
                    id="username"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    placeholder={__('Leave empty to use email')}
                  />
                  <p className="text-xs text-muted-foreground">
                    {__('Username will be generated from email if left empty')}
                  </p>
                </div>
              )}
              
              <div className="space-y-2">
                <Label htmlFor="password">
                  {mode === 'create' ? __('Password') : __('New Password')}
                </Label>
                <Input
                  id="password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder={mode === 'create' ? __('Leave empty to auto-generate') : __('Leave empty to keep current')}
                />
                {mode === 'create' && (
                  <p className="text-xs text-muted-foreground">
                    {__('A secure password will be generated if left empty')}
                  </p>
                )}
              </div>
              
              {mode === 'create' && (
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="send_email"
                    checked={sendEmail}
                    onCheckedChange={(checked) => setSendEmail(Boolean(checked))}
                  />
                  <Label htmlFor="send_email" className="cursor-pointer">
                    {__('Send welcome email with login credentials')}
                  </Label>
                </div>
              )}
            </CardContent>
          </Card>
        </FormSection>
        
        {/* Billing Address */}
        <FormSection id="billing">
          <Card>
            <CardHeader>
              <CardTitle>{__('Billing Address')}</CardTitle>
              <CardDescription>
                {__('Customer billing information')}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="billing_company">{__('Company')}</Label>
                <Input
                  id="billing_company"
                  value={billingCompany}
                  onChange={(e) => setBillingCompany(e.target.value)}
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="billing_address_1">{__('Address Line 1')}</Label>
                <Input
                  id="billing_address_1"
                  value={billingAddress1}
                  onChange={(e) => setBillingAddress1(e.target.value)}
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="billing_address_2">{__('Address Line 2')}</Label>
                <Input
                  id="billing_address_2"
                  value={billingAddress2}
                  onChange={(e) => setBillingAddress2(e.target.value)}
                />
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="billing_city">{__('City')}</Label>
                  <Input
                    id="billing_city"
                    value={billingCity}
                    onChange={(e) => setBillingCity(e.target.value)}
                  />
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="billing_state">{__('State / Province')}</Label>
                  <Input
                    id="billing_state"
                    value={billingState}
                    onChange={(e) => setBillingState(e.target.value)}
                  />
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="billing_postcode">{__('Postcode / ZIP')}</Label>
                  <Input
                    id="billing_postcode"
                    value={billingPostcode}
                    onChange={(e) => setBillingPostcode(e.target.value)}
                  />
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="billing_country">{__('Country')}</Label>
                  <Input
                    id="billing_country"
                    value={billingCountry}
                    onChange={(e) => setBillingCountry(e.target.value)}
                    placeholder="ID"
                  />
                </div>
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="billing_phone">{__('Phone')}</Label>
                <Input
                  id="billing_phone"
                  type="tel"
                  value={billingPhone}
                  onChange={(e) => setBillingPhone(e.target.value)}
                />
              </div>
            </CardContent>
          </Card>
        </FormSection>
        
        {/* Shipping Address */}
        <FormSection id="shipping">
          <Card>
            <CardHeader>
              <CardTitle>{__('Shipping Address')}</CardTitle>
              <CardDescription>
                {__('Customer shipping information')}
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex items-center space-x-2 mb-4">
                <Checkbox
                  id="copy_billing"
                  checked={copyBilling}
                  onCheckedChange={(checked) => setCopyBilling(Boolean(checked))}
                />
                <Label htmlFor="copy_billing" className="cursor-pointer">
                  {__('Same as billing address')}
                </Label>
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="shipping_company">{__('Company')}</Label>
                <Input
                  id="shipping_company"
                  value={shippingCompany}
                  onChange={(e) => setShippingCompany(e.target.value)}
                  disabled={copyBilling}
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="shipping_address_1">{__('Address Line 1')}</Label>
                <Input
                  id="shipping_address_1"
                  value={shippingAddress1}
                  onChange={(e) => setShippingAddress1(e.target.value)}
                  disabled={copyBilling}
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="shipping_address_2">{__('Address Line 2')}</Label>
                <Input
                  id="shipping_address_2"
                  value={shippingAddress2}
                  onChange={(e) => setShippingAddress2(e.target.value)}
                  disabled={copyBilling}
                />
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="shipping_city">{__('City')}</Label>
                  <Input
                    id="shipping_city"
                    value={shippingCity}
                    onChange={(e) => setShippingCity(e.target.value)}
                    disabled={copyBilling}
                  />
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="shipping_state">{__('State / Province')}</Label>
                  <Input
                    id="shipping_state"
                    value={shippingState}
                    onChange={(e) => setShippingState(e.target.value)}
                    disabled={copyBilling}
                  />
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="shipping_postcode">{__('Postcode / ZIP')}</Label>
                  <Input
                    id="shipping_postcode"
                    value={shippingPostcode}
                    onChange={(e) => setShippingPostcode(e.target.value)}
                    disabled={copyBilling}
                  />
                </div>
                
                <div className="space-y-2">
                  <Label htmlFor="shipping_country">{__('Country')}</Label>
                  <Input
                    id="shipping_country"
                    value={shippingCountry}
                    onChange={(e) => setShippingCountry(e.target.value)}
                    placeholder="ID"
                    disabled={copyBilling}
                  />
                </div>
              </div>
            </CardContent>
          </Card>
        </FormSection>
      </VerticalTabForm>
      
      {!hideSubmitButton && (
        <div className="mt-6">
          <Button type="submit" disabled={submitting} className="w-full md:w-auto">
            {submitting 
              ? (mode === 'create' ? __('Creating...') : __('Saving...'))
              : (mode === 'create' ? __('Create Customer') : __('Save Changes'))
            }
          </Button>
        </div>
      )}
    </form>
  );
}
