"use client";

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { getCurrentCustomer, signOut } from '@/src/services/web/auth.services';
import { useCustomToast } from '@/src/hooks/web/useCustomToast';

interface CustomerData {
  id: number;
  name: string;
  email: string;
  is_verified: boolean;
  created_at?: string;
}

export default function ProfilePage() {
  const router = useRouter();
  const { showToast } = useCustomToast();
  const [customer, setCustomer] = useState<CustomerData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadCustomerData();
    console.log(customer);
  }, []);

  const loadCustomerData = async () => {
    try {
      const response = await getCurrentCustomer();
      
      if (response.data.success && response.data.user) {
        setCustomer(response.data.user);
      } else {
        showToast({
          title: 'Error',
          description: 'Failed to load profile data',
          type: 'error',
        });
        router.push('/web-auth');
      }
    } catch (error: any) {
      console.error('Error loading customer data:', error);
      console.error('Error response:', error?.response?.data);
      showToast({
        title: 'Error',
        description: 'Please login to view your profile',
        type: 'error',
      });
      router.push('/web-auth');
    } finally {
      setLoading(false);
    }
  };

  const handleSignOut = async () => {
    try {
      await signOut();
      showToast({
        title: 'Success',
        description: 'Signed out successfully',
        type: 'success',
      });
      router.push('/');
    } catch (error) {
      console.error('Sign out error:', error);
      showToast({
        title: 'Error',
        description: 'Failed to sign out',
        type: 'error',
      });
    }
  };


  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-teal-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Loading profile...</p>
        </div>
      </div>
    );
  }

  const generateUserId = (userId:number) => {
    return `#${userId.toString().padStart(6, '0')}`;
  }

  if (!customer) {
    return null;
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="bg-white rounded-lg shadow-md overflow-hidden mb-6">
          <div className="bg-gradient-to-r from-teal-500 to-teal-600 h-32"></div>
          <div className="px-6 pb-6">
            <div className="flex flex-col sm:flex-row items-center sm:items-end -mt-16 sm:-mt-7">
              <div className="relative">
                <div className="w-24 h-24 sm:w-32 sm:h-32 rounded-full bg-white border-4 border-white shadow-lg flex items-center justify-center">
                  <span className="text-4xl sm:text-5xl font-bold text-teal-600">
                    {customer.name.charAt(0).toUpperCase()}
                  </span>
                </div>
                {customer.is_verified && (
                  <div className="absolute bottom-0 right-0 bg-green-500 rounded-full p-2 border-2 border-white">
                    <svg className="w-4 h-4 text-white" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                    </svg>
                  </div>
                )}
              </div>
              <div className="mt-4 sm:mt-0 sm:ml-6 text-center sm:text-left flex-1">
                <h1 className="text-2xl sm:text-3xl font-bold text-gray-900">{customer.name}</h1>
                <p className="text-gray-600 mt-1">{customer.email}</p>
                {customer.is_verified && (
                  <span className="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800 mt-2">
                    Verified Account
                  </span>
                )}
              </div>
              <button
                onClick={handleSignOut}
                className="mt-4 sm:mt-0 px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-md transition"
              >
                Sign Out
              </button>
            </div>
          </div>
        </div>

        {/* Profile Details */}
        <div className="bg-white rounded-lg shadow-md p-6 mb-6">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">Profile Information</h2>
          <div className="space-y-4">
            <div className="flex items-start border-b border-gray-200 pb-4">
              <div className="flex-shrink-0">
                <svg className="w-5 h-5 text-gray-400 mt-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                </svg>
              </div>
              <div className="ml-4 flex-1">
                <p className="text-sm font-medium text-gray-500">Full Name</p>
                <p className="mt-1 text-base text-gray-900">{customer.name}</p>
              </div>
            </div>

            <div className="flex items-start border-b border-gray-200 pb-4">
              <div className="flex-shrink-0">
                <svg className="w-5 h-5 text-gray-400 mt-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
              </div>
              <div className="ml-4 flex-1">
                <p className="text-sm font-medium text-gray-500">Email Address</p>
                <p className="mt-1 text-base text-gray-900">{customer.email}</p>
              </div>
            </div>

            <div className="flex items-start border-b border-gray-200 pb-4">
              <div className="flex-shrink-0">
                <svg className="w-5 h-5 text-gray-400 mt-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <div className="ml-4 flex-1">
                <p className="text-sm font-medium text-gray-500">Account Status</p>
                <p className="mt-1 text-base text-gray-900">
                  {customer.is_verified ? (
                    <span className="text-green-600 font-medium">Verified</span>
                  ) : (
                    <span className="text-yellow-600 font-medium">Pending Verification</span>
                  )}
                </p>
              </div>
            </div>

            <div className="flex items-start">
              <div className="flex-shrink-0">
                <svg className="w-5 h-5 text-gray-400 mt-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
                </svg>
              </div>
              <div className="ml-4 flex-1">
                <p className="text-sm font-medium text-gray-500">Customer ID</p>
                <p className="mt-1 text-base text-gray-900 font-mono">{generateUserId(customer.id)}</p>
              </div>
            </div>
          </div>
        </div>

        {/* Quick Actions */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-semibold text-gray-900 mb-4">Quick Actions</h2>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <button
              onClick={() => router.push('/my-application')}
              className="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition"
            >
              <div className="flex-shrink-0">
                <svg className="w-6 h-6 text-teal-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
              </div>
              <div className="ml-4 text-left">
                <p className="text-sm font-medium text-gray-900">My Applications</p>
                <p className="text-xs text-gray-500">View all your applications</p>
              </div>
            </button>

            <button
              onClick={() => router.push('/')}
              className="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition"
            >
              <div className="flex-shrink-0">
                <svg className="w-6 h-6 text-teal-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                </svg>
              </div>
              <div className="ml-4 text-left">
                <p className="text-sm font-medium text-gray-900">Home</p>
                <p className="text-xs text-gray-500">Go to homepage</p>
              </div>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}