'use client';

import { useAuth } from '@/contexts/AuthContext';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Card, CardContent } from '@/components/ui/card';
import { ProfilePhotoPicker } from '@/components/ui/ProfilePhotoPicker';
import {
  PortalShell,
  PortalSection,
} from '@/components/portal/Portal';
import { getUploadUrl } from '@/lib/api';
import { removeAvatar, uploadAvatar } from '@/lib/avatar';
import { UserRound } from 'lucide-react';
import { useState } from 'react';
import { AccountDeletionCard } from '@/components/account/AccountDeletionCard';

export default function CustomerProfilePage() {
  const { user, refreshUser } = useAuth();
  const [avatarUploading, setAvatarUploading] = useState(false);
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null);
  const [error, setError] = useState('');

  const handleAvatarChange = async (file: File | null, previewUrl: string | null) => {
    if (!file && !user?.avatarUrl) {
      setAvatarPreview(null);
      return;
    }

    const previousBlob = avatarPreview?.startsWith('blob:') ? avatarPreview : null;
    setAvatarPreview(previewUrl);
    setAvatarUploading(true);
    setError('');

    try {
      if (file) {
        const res = await uploadAvatar(file);
        await refreshUser();
        if (res.data.avatarUrl) {
          setAvatarPreview(getUploadUrl(res.data.avatarUrl));
        }
      } else {
        await removeAvatar();
        await refreshUser();
        setAvatarPreview(null);
      }
      if (previousBlob) URL.revokeObjectURL(previousBlob);
      if (previewUrl?.startsWith('blob:')) URL.revokeObjectURL(previewUrl);
    } catch (err: unknown) {
      if (previewUrl?.startsWith('blob:')) URL.revokeObjectURL(previewUrl);
      setAvatarPreview(user?.avatarUrl ? getUploadUrl(user.avatarUrl) : null);
      setError(err instanceof Error ? err.message : 'Failed to update profile photo');
    } finally {
      setAvatarUploading(false);
    }
  };

  return (
    <DashboardLayout role="customer" title="Profile">
      <PortalShell>
        <Card className="overflow-hidden border-0 bg-slate-900 text-white shadow-md">
          <CardContent className="p-6">
            <div className="flex flex-wrap items-start justify-between gap-4">
              <div>
                <h2 className="text-xl font-bold">
                  {user?.firstName} {user?.lastName}
                </h2>
                <p className="mt-1 text-sm text-slate-300">{user?.email || user?.phone}</p>
              </div>
            </div>
          </CardContent>
        </Card>

        <PortalSection icon={UserRound} title="Account" description="Your customer profile details">
          <ProfilePhotoPicker
            previewUrl={
              avatarPreview ??
              (user?.avatarUrl ? getUploadUrl(user.avatarUrl) : null)
            }
            onChange={handleAvatarChange}
            disabled={avatarUploading}
            helperText={
              avatarUploading
                ? 'Uploading profile photo…'
                : 'Your photo appears in messages with workers.'
            }
            pendingLabel={avatarUploading ? 'Uploading…' : undefined}
          />
          {error ? <p className="mt-3 text-sm text-red-500">{error}</p> : null}

          <div className="mt-6 space-y-3 border-t border-border pt-5">
            <p className="text-sm font-semibold text-slate-900">Contact info</p>
            <dl className="grid gap-3 text-sm sm:grid-cols-2">
              <div>
                <dt className="text-muted">Email</dt>
                <dd className="mt-0.5 font-medium text-slate-900">{user?.email || '—'}</dd>
              </div>
              <div>
                <dt className="text-muted">Phone</dt>
                <dd className="mt-0.5 font-medium text-slate-900">{user?.phone || '—'}</dd>
              </div>
            </dl>
          </div>
        </PortalSection>

        <AccountDeletionCard />
      </PortalShell>
    </DashboardLayout>
  );
}
