'use client';

import type { Result } from '@/lib/contracts/Result';
import type { ProfileViewData } from '@/lib/view-data/ProfileViewData';
import { ProfileSettingsTemplate } from '@/templates/ProfileSettingsTemplate';
import { 
  SharedBox, 
  SharedStack, 
  SharedText, 
  SharedIcon,
  SharedProgressLine
} from '@/components/shared/UIComponents';
import { ShieldAlert } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useState } from 'react';
import { ClientWrapperProps } from '@/lib/contracts/components/ComponentContracts';

interface ProfileSettingsPageClientProps extends ClientWrapperProps<ProfileViewData> {
  onSave: (updates: { bio?: string; country?: string }) => Promise<Result<void, string>>;
}

export function ProfileSettingsPageClient({ viewData, onSave }: ProfileSettingsPageClientProps) {
  const router = useRouter();
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  const [bio, setBio] = useState(viewData.driver.bio || '');
  const [country, setCountry] = useState(viewData.driver.countryCode);

  const handleSave = async () => {
    setIsSaving(true);
    setError(null);
    try {
      const result = await onSave({ bio, country });
      if (result.isErr()) {
        setError(result.getError());
      } else {
        router.refresh();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save settings');
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <>
      <SharedProgressLine isLoading={isSaving} />
      {error && (
        <SharedBox position="fixed" top={4} right={4} zIndex={50} maxWidth="md">
          <SharedBox bg="bg-error-red/10" p={4} rounded="md" border borderColor="border-error-red/20">
            <SharedStack direction="row" align="center" gap={3}>
              <SharedIcon icon={ShieldAlert} size={5} color="text-error-red" />
              <SharedBox>
                <SharedText weight="bold" color="text-error-red">Update Failed</SharedText>
                <SharedText size="sm" color="text-error-red/80">{error}</SharedText>
              </SharedBox>
            </SharedStack>
          </SharedBox>
        </SharedBox>
      )}
      <ProfileSettingsTemplate
        viewData={viewData}
        bio={bio}
        country={country}
        onBioChange={setBio}
        onCountryChange={setCountry}
        onSave={handleSave}
      />
    </>
  );
}
