'use client';

import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import { ProfileSettingsTemplate } from '@/templates/ProfileSettingsTemplate';
import type { ProfileViewData } from '@/lib/view-data/ProfileViewData';
import type { Result } from '@/lib/contracts/Result';
import { ProgressLine } from '@/components/shared/ux/ProgressLine';
import { InlineNotice } from '@/components/shared/ux/InlineNotice';
import { Box } from '@/ui/Box';

interface ProfileSettingsPageClientProps {
  viewData: 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 (
    <>
      <ProgressLine isLoading={isSaving} />
      {error && (
        <Box position="fixed" top={4} right={4} zIndex={50} maxWidth="md">
          <InlineNotice
            variant="error"
            title="Update Failed"
            message={error}
          />
        </Box>
      )}
      <ProfileSettingsTemplate
        viewData={viewData}
        bio={bio}
        country={country}
        onBioChange={setBio}
        onCountryChange={setCountry}
        onSave={handleSave}
      />
    </>
  );
}
