'use client';

import type {ReactNode} from 'react';
import {accountStatusLabel,type AccountAccessSummary} from '@/lib/account-access';
import {Check,LoaderCircle,Mail,Smartphone,ShieldBan} from 'lucide-react';
import type {CustomerUser} from '@/lib/auth-input';
import type {Locale} from '@/lib/catalog';
import type {DashboardData} from '@/lib/dashboard';
import {dashboardLabel} from '@/lib/dashboard-copy';
import type {verificationPresentation} from '@/lib/identity-presentation';
import {PersianBirthDate} from './persian-birth-date';

type ProfilePanelData={
 user:Pick<CustomerUser,'id'|'name'|'username'|'email'|'phone'>;
 account:DashboardData['account'];
 locale:Locale;
 verification:ReturnType<typeof verificationPresentation>;
 access?:AccountAccessSummary;
 hasBankOwnership:boolean;
 avatar:ReactNode;
};

export type CustomerProfilePanelsProps=ProfilePanelData&(
 |{readOnly:true;busy?:never;onSave?:never;onAddEmail?:never}
 |{readOnly?:false;busy:boolean;onSave:(payload:Record<string,unknown>)=>unknown;onAddEmail:()=>void}
);

function Panel({title,children,className=''}:{title?:string;children:ReactNode;className?:string}){
 return <section className={`dash-card ${className}`}>{title&&<div className="dash-card-heading"><h2>{title}</h2></div>}{children}</section>;
}

/** The member's actual profile view. All session, image access and writes belong to the caller. */
export function CustomerProfilePanels(props:CustomerProfilePanelsProps){
 const {user,account,locale,verification,hasBankOwnership,avatar,access,readOnly=false,busy=false}=props;
 const restricted=!!access&&access.status!=='active',accessLabel=access?accountStatusLabel(access.status,locale):'';
 const fullName=[account.first_name,account.last_name].filter(Boolean).join(' ')||user.name||user.username||dashboardLabel('personal',locale);
 const verified=account.verification_status==='verified';
 const formKey=readOnly?JSON.stringify([user.id,account]):`${account.updated_at??fullName}:${account.national_id??''}`;
 const joined=account.created_at&&!Number.isNaN(Date.parse(account.created_at))?new Intl.DateTimeFormat(locale,{dateStyle:'medium'}).format(new Date(account.created_at)):'—';
 return <>
  <Panel className="dash-profile-banner">
   {restricted&&<div className="profile-access-restriction" role="alert"><ShieldBan size={23}/><div><strong>{accessLabel}</strong><p>{locale==='en'?'Account access is disabled. Contact support for assistance.':locale==='ar'?'الوصول إلى الحساب معطّل. يرجى التواصل مع الدعم.':'دسترسی به حساب غیرفعال است. برای پیگیری با پشتیبانی تماس بگیرید.'}</p></div></div>}
   <div className="dash-profile-overview">{avatar}<div><span className="dash-eyebrow">حساب پلانک شما</span><h2>{fullName}</h2><p dir="ltr">{user.email||user.phone||user.username}</p></div><span className={`dash-status ${restricted?'status-suspended':'status-'+verification.tone}`} aria-live="polite">{restricted?accessLabel:verification.label}</span></div>
   <div className="dash-profile-facts"><div><span>عضویت در پلانک</span><strong>{joined}</strong></div><div><span>نام کاربری</span><strong dir="ltr">{user.username||'—'}</strong></div><div><span>احراز هویت</span><strong>{verification.label}</strong></div><div aria-live="polite" aria-atomic="true"><span>سطح فعلی حساب</span><strong>{verification.levelLabel}</strong></div></div>
   {verification.temporary&&<div className="identity-temporary-summary" role="status">{verification.expiresText&&<strong>{verification.expiresText}</strong>}<p>{verification.detail}</p></div>}
  </Panel>
  <Panel title="اطلاعات من">
   <form key={formKey} className="dash-form" onSubmit={e=>{
    e.preventDefault();
    if(props.readOnly||restricted)return;
    const f=new FormData(e.currentTarget);
    void props.onSave({first_name:f.get('first_name'),last_name:f.get('last_name'),birth_date:f.get('birth_date'),...(account.national_id_editable===false?{}:{national_id:f.get('national_id')})});
   }}>
    <div className="dash-form-grid">
     <label>نام<input name="first_name" autoComplete="given-name" required maxLength={80} defaultValue={account.first_name} disabled={readOnly||restricted||verified}/></label>
     <label>نام خانوادگی<input name="last_name" autoComplete="family-name" required maxLength={80} defaultValue={account.last_name} disabled={readOnly||restricted||verified}/></label>
     <PersianBirthDate defaultValue={account.birth_date||''} disabled={readOnly||restricted||verified}/>
     <label>کد ملی<input name="national_id" dir="ltr" inputMode="numeric" autoComplete="off" required={account.national_id_editable!==false} minLength={10} maxLength={10} defaultValue={account.national_id||''} disabled={readOnly||restricted} readOnly={readOnly||restricted||account.national_id_editable===false||verified||account.verification_status==='pending'||hasBankOwnership} placeholder={account.national_id_editable===false?'از بخش احراز هویت ثبت کنید':'کد ملی ده‌رقمی'}/>{account.national_id_editable===false&&<small>{account.national_id?'کد ملی ثبت‌شده در پرونده احراز هویت شما':'برای ثبت کد ملی، احراز هویت بالای داشبورد را تکمیل کنید.'}</small>}</label>
    </div>
    <div className="dash-form-footer"><p>{verified?'تغییر مشخصات تأییدشده از طریق پشتیبانی انجام می‌شود.':'برای تأیید مشخصات، از دکمه احراز هویت بالای داشبورد استفاده کنید.'}</p><button className="dash-primary" disabled={readOnly||restricted||busy||verified}>{busy?<LoaderCircle className="account-spinner" size={17}/>:<Check size={17}/>}ذخیره اطلاعات</button></div>
   </form>
  </Panel>
  <Panel title="اطلاعات تماس">
   <div className="dash-info-row"><span><Mail size={20}/>ایمیل</span><strong dir="ltr">{user.email||'ثبت نشده'}</strong>{!user.email&&<button className="dash-link" disabled={readOnly||restricted} onClick={props.readOnly||restricted?undefined:props.onAddEmail}>افزودن ایمیل</button>}</div>
   <div className="dash-info-row"><span><Smartphone size={20}/>شماره موبایل</span><strong dir="ltr">{user.phone||'ثبت نشده'}</strong></div>
  </Panel>
 </>;
}
