'use client';
import {usePricing} from '../../use-pricing';
import {useEffect,useState} from 'react';
import {RequestRecord} from '../browse';
import {mutate} from '../../controls';
import {Switch} from '@/components/ui/switch';
import {Progress} from '@/components/ui/progress';
import {ShieldCheck,MapPin} from 'lucide-react';
import OfferPhotoPicker,{type OfferPhoto} from '../../offer-photo-picker';

export default function Detail({id,preview=false}:{id:string,preview?:boolean}){
  const pricing=usePricing();
  const[r,setR]=useState<RequestRecord|null>(null),[error,setError]=useState(''),[success,setSuccess]=useState('');
  const[promoted,setPromoted]=useState(false),[agency,setAgency]=useState(false),[credit,setCredit]=useState(false),[busy,setBusy]=useState(false);
  const[photos,setPhotos]=useState<OfferPhoto[]>([]),[progress,setProgress]=useState(0),[sent,setSent]=useState(false);
  useEffect(()=>{fetch('/api/market?view=request&id='+encodeURIComponent(id)).then(async res=>{const data=await res.json() as RequestRecord & {error:string};if(!res.ok)throw Error(data.error);setR(data)}).catch(e=>setError(e.message))},[id]);
  useEffect(()=>{if(r&&location.hash==='#trimite-oferta')document.getElementById('trimite-oferta')?.scrollIntoView()},[r]);
  const cost=pricing.freeOffersActive?0:(r?.urgent?pricing.urgentBid:pricing.bid)+(promoted?pricing.promoteOffer:0);
  return <div className="panel">
    {preview&&<p className="notice">Previzualizarea formularului de ofertă. Trimiterea este dezactivată și nu se consumă credite.</p>}
    <a href="/cereri" className="text-link">← Înapoi la cereri</a>
    {error&&<p className="error" role="alert">{error}</p>}
    {r?<><h1 style={{fontSize:36}}>{r.title}</h1><p className="location"><MapPin size={17}/>{r.city} · {r.county} · {r.zone}</p><div className="details"><span>{r.deal}</span><span>{r.type}</span><span>{r.area}+ m²</span>{r.rooms&&<span>{r.rooms} camere</span>}{r.floor&&<span>Etaj: {r.floor}</span>}</div><div className="budget"><span>Buget maxim</span><strong>{r.budget.toLocaleString('ro-RO')} €</strong></div><p style={{whiteSpace:'pre-wrap',margin:'22px 0',lineHeight:1.8}}>{r.description}</p><p className="demo-note">Expiră la {new Date(r.expires).toLocaleDateString('ro-RO')}</p>
      <button className="text-link" onClick={async()=>{try{await mutate({action:'favorite',id});setSuccess('Adăugată la favorite.')}catch(e){setError((e as Error).message)}}}>♡ Adaugă la favorite</button>
      <div className="notice flex gap-3"><ShieldCheck/><p>Telefonul solicitantului și chatul devin disponibile doar dacă oferta ta este acceptată.</p></div>
      {r.isOwner&&!preview?<a className="button" href="/cont">Administrează cererea</a>:<><h2 id="trimite-oferta" style={{scrollMarginTop:24}}>Trimite oferta ta</h2>
        {pricing.freeOffersActive&&<p className="notice">Testare gratuită până la {new Date(pricing.freeOffersUntil).toLocaleString('ro-RO',{timeZone:'Europe/Bucharest',dateStyle:'short',timeStyle:'short'})}, ora României. Trimiterea ofertelor, inclusiv a celor promovate, nu consumă credite în această perioadă.</p>}
        <p className="demo-note">Cost total: {cost} {cost===1?'credit':'credite'}</p>
        {sent?<a href="/cont" className="button mt-4">Vezi oferta în cont →</a>:<form onSubmit={async e=>{
          e.preventDefault();if(preview||busy)return;setBusy(true);setError('');setSuccess('');setProgress(0);
          const fields=Object.fromEntries(new FormData(e.currentTarget));
          try{
            const photoIds:string[]=[];
            for(let i=0;i<photos.length;i++){
              const photo=photos[i];let assetId=photo.assetId;
              if(!assetId){const response=await fetch('/api/offer-images',{method:'POST',headers:{'Content-Type':photo.file.type},body:photo.file});const uploaded=await response.json() as {id:string,error?:string};if(!response.ok)throw Error(uploaded.error||'Fotografia nu a putut fi încărcată.');assetId=uploaded.id;setPhotos(current=>current.map(p=>p.localId===photo.localId?{...p,assetId}:p));}
              photoIds.push(assetId);setProgress(Math.round((i+1)/photos.length*100));
            }
            await mutate({...fields,action:'offer',id,promoted,agency,creditAccepted:credit,photoIds,expectedCost:cost});
            setSent(true);setSuccess('Oferta și fotografiile au fost trimise. Le găsești în contul tău.');
          }catch(e){setError((e as Error).message)}finally{setBusy(false)}
        }}>
          <div className="form-grid">
            <label className="field full">Titlul ofertei<input name="title" required minLength={8} maxLength={160} disabled={busy}/></label>
            <OfferPhotoPicker photos={photos} setPhotos={setPhotos} disabled={busy}/>
            <label className="field">Preț (€)<input name="price" type="number" min="1" required disabled={busy}/></label>
            <label className="field">Locație<input name="location" required maxLength={200} disabled={busy}/></label>
            <label className="field full">Descriere și detalii ale proprietății<textarea name="description" rows={5} required minLength={20} maxLength={3000} disabled={busy}/></label>
            <label className="field full">Comision<input name="commission" placeholder="Fără comision / 2% / altă valoare" required maxLength={80} disabled={busy}/></label>
            <label className="flex items-center gap-3"><Switch checked={agency} onCheckedChange={setAgency} disabled={busy}/> Sunt agent imobiliar</label>
            <label className="flex items-center gap-3"><Switch checked={credit} onCheckedChange={setCredit} disabled={busy}/> Accept credit bancar</label>
            <label className="full flex items-center gap-3"><Switch checked={promoted} onCheckedChange={setPromoted} disabled={busy}/> Promovează oferta · {pricing.freeOffersActive?'gratuit în perioada de testare':'+'+pricing.promoteOffer+' credite'}</label>
          </div>
          {busy&&photos.length>0&&<div role="status" className="mt-5"><p className="demo-note">Încărcare fotografii: {progress}%</p><Progress value={progress}/></div>}
          <button disabled={busy||preview} className="button mt-6">{preview?'Trimitere dezactivată în previzualizare':busy?'Se trimite…':cost===0?'Trimite oferta gratuit':'Trimite oferta · '+cost+' credite'}</button>
        </form>}
      </>}
      {success&&<p className="success" role="status">{success}</p>}
    </>:!error&&<p>Se încarcă cererea…</p>}
  </div>;
}
