"use client";
import {useState,type ComponentType} from "react";
import {Activity,ArrowDownRight,ArrowUpRight,Bean,Beef,BookOpen,CalendarDays,Carrot,ChevronRight,CookingPot,CupSoda,Droplet,Droplets,Fish,Footprints,GlassWater,HeartPulse,Leaf,Salad,Utensils,Wheat} from "lucide-react";
import {bn,dateLabel,type Entry,type LipidKey} from "./journal";
import {aggregateDays,shiftDate} from "./insight-data";

type Icon=ComponentType<{size?:number;className?:string}>;
type TileProps={name:string;icon:Icon;value:string;unit:string;caption:string;detail:string;onClick:()=>void;tone:string;delta?:number};
function MetricTile({name,icon:Symbol,value,unit,caption,detail,onClick,tone,delta}:TileProps){
  return <button type="button" className={"metric "+tone} onClick={onClick}>
    <span className="metric-name"><span className="metric-icon"><Symbol size={19}/></span>{name}</span>
    <span className="metric-reading"><b>{value}</b> <small>{unit}</small></span>
    <span className="metric-caption">{caption}</span>
    <span className="metric-detail">{delta!==undefined&&delta!==0&&(delta>0?<ArrowUpRight size={15}/>:<ArrowDownRight size={15}/>)}{detail}<ChevronRight size={15} className="metric-chevron"/></span>
  </button>
}
export function DashboardMetrics({daily,labs,now,onLabs,onDay,onWeek,onAdd}:{daily:Entry[];labs:Entry[];now:string;onLabs:()=>void;onDay:(d:string)=>void;onWeek:()=>void;onAdd:()=>void}){
  const dates=aggregateDays(daily);
  const latestBP=[...dates.keys()].filter(d=>dates.get(d)!.count>0).sort().at(-1);
  const bp=latestBP?dates.get(latestBP):undefined;
  const week=Array.from({length:7},(_,i)=>shiftDate(now,i-6));
  const active=week.filter(d=>dates.get(d)?.walk!=null);
  const minutes=active.reduce((sum,d)=>sum+(dates.get(d)?.walk??0),0);
  const foodDays=week.filter(d=>(dates.get(d)?.meals??0)>0).length;
  const latest=labs[0], prior=labs.find(l=>latest&&l.day<latest.day);
  const labCards:{key:LipidKey;name:string;icon:Icon;tone:string}[]=[
    {key:"ldl",name:"LDL কোলেস্টেরল",icon:Droplet,tone:"mint"},
    {key:"tg",name:"ট্রাইগ্লিসারাইড",icon:Activity,tone:"sand"},
    {key:"hdl",name:"HDL কোলেস্টেরল",icon:Droplets,tone:"lilac"}
  ];
  return <section aria-label="স্বাস্থ্যের প্রধান সূচক" className="metricboard">
    <div className="metricboard-head"><h2>স্বাস্থ্যের প্রধান সূচক</h2><button className="link" onClick={onLabs}>{latest?"মোট কোলেস্টেরল "+bn(latest.values.total!)+" mg/dL · রিপোর্ট দেখো":"লিপিড প্রোফাইল দেখো"}</button></div>
    <div className="metricgrid">{labCards.map(c=>{
      const n=latest?.values[c.key],old=prior?.values[c.key],delta=n!==undefined&&old!==undefined?Math.round((n-old)*100)/100:undefined;
      const change=delta===undefined?(latest?"আগের তারিখের রিপোর্ট নেই":"পরীক্ষার ফল যোগ করো"):delta===0?"আগের রিপোর্টের সমান":bn(Math.abs(delta))+" mg/dL "+(delta>0?"বেড়েছে":"কমেছে");
      return <MetricTile key={c.key} name={c.name} icon={c.icon} tone={c.tone} value={n===undefined?"—":bn(n)} unit="mg/dL" caption={latest?dateLabel(latest.day,true):"রিপোর্ট নেই"} detail={change} delta={delta} onClick={onLabs}/>
    })}
    <MetricTile name="রক্তচাপ" icon={HeartPulse} tone="rose" value={bp?bn(Math.round(bp.sys/bp.count))+"/"+bn(Math.round(bp.dia/bp.count)):"—"} unit="mmHg" caption={latestBP?dateLabel(latestBP,true):"এখনও মাপ লেখা হয়নি"} detail={bp?"সেদিনের "+bn(bp.count)+"টি মাপের গড়":"প্রথম মাপ লেখো"} onClick={()=>latestBP?onDay(latestBP):onAdd()}/>
    <MetricTile name="সাত দিনের হাঁটা" icon={Footprints} tone="sage" value={active.length?bn(minutes):"—"} unit="মিনিট" caption={dateLabel(week[0])+" – "+dateLabel(now)} detail={active.length?bn(active.length)+" দিনের সময় লেখা হয়েছে":"হাঁটার সময় লেখো"} onClick={active.length?onWeek:onAdd}/>
    <MetricTile name="খাবারের দিনলিপি" icon={BookOpen} tone="peach" value={bn(foodDays)+"/৭"} unit="দিন" caption={dateLabel(week[0])+" – "+dateLabel(now)} detail={foodDays?"খাবারের বিবরণ দেখো":"প্রথম খাবারের বিবরণ লেখো"} onClick={foodDays?onWeek:onAdd}/>
    </div></section>
}

const portions=[
  {name:"শাকসবজি",fraction:"১/২",icon:Carrot,examples:"লাউ, শাক, ঢেঁড়স, শসা বা ফুলকপি।",reason:"পাতে আঁশ ও খাবারের বৈচিত্র্য বাড়ায়। আলু শর্করার অংশে ধরো।",color:"greens"},
  {name:"প্রোটিন",fraction:"১/৪",icon:Fish,examples:"এক টুকরো মাছের ঝোল, চামড়া ছাড়া মুরগি বা ছোলা।",reason:"মাছ ও ডালজাতীয় খাবার প্রোটিন দেয়। চর্বিযুক্ত মাংস কমাতে এগুলো বেছে নিতে পারো।",color:"protein"},
  {name:"ভাত বা রুটি",fraction:"১/৪",icon:Wheat,examples:"পরিমিত ভাত বা আটার রুটি। পছন্দ হলে লাল চাল বেছে নাও।",reason:"ভাত বা রুটি শক্তি দেয়। প্লেটের এই অংশটি পরিমাণ বুঝতে সাহায্য করে।",color:"grains"}
] as const;
const goals=[
  {tab:"LDL",title:"রান্নার চর্বি বেছে নাও",icon:Droplet,less:"ঘি, মাখন ও চর্বিযুক্ত মাংস",more:"মেপে তরল উদ্ভিজ্জ তেল, মাছের ঝোল",left:Beef,right:Fish,why:"ঘি ও মাংসের চর্বিতে স্যাচুরেটেড ফ্যাট বেশি। এর কিছু অংশ অসম্পৃক্ত চর্বি দিয়ে বদলালে LDL কমাতে সাহায্য করে।",idea:"মাছ ডুবো তেলে না ভেজে অল্প সয়াবিন তেলে ঝোল রান্না করো।",source:"American Heart Association",url:"https://www.heart.org/en/healthy-living/healthy-eating/eat-smart/fats/healthy-cooking-oils"},
  {tab:"ট্রাইগ্লিসারাইড",title:"চিনি ও সাদা ভাতের পরিমাণ খেয়াল করো",icon:Activity,less:"কোমল পানীয়, মিষ্টি চা, বাড়তি ভাত",more:"পানি, চিনি ছাড়া চা, ডাল ও সবজি",left:CupSoda,right:Bean,why:"বেশি যোগ করা চিনি ও পরিশোধিত শর্করা ট্রাইগ্লিসারাইড বাড়াতে পারে। মিষ্টি পানীয় কমানো ও ভাতের পরিমাণ সামলানো কাজে দেয়।",idea:"দুপুরে দ্বিতীয়বার ভাত নেওয়ার সময় অল্প ভাতের সঙ্গে ডাল ও সবজি নাও।",source:"National Lipid Association",url:"https://www.lipid.org/wp-content/uploads/lifestyle_changes_to_reduce_triglycerides.final_edits.7.17.16_0.pdf"},
  {tab:"রক্তচাপ",title:"কোন খাবারে লবণ বেশি, দেখে নাও",icon:HeartPulse,less:"নোনতা চানাচুর, আচার, পাতে বাড়তি লবণ",more:"লবণ ছাড়া ছোলা, শসা ও লেবু",left:CookingPot,right:Salad,why:"বেশি সোডিয়াম রক্তচাপ বাড়াতে পারে। লবণ কমানো এবং নিয়মিত শাকসবজি ও ডাল খাওয়া রক্তচাপ নিয়ন্ত্রণে সাহায্য করে।",idea:"বিকেলের নাশতায় সেদ্ধ ছোলায় শসা, লেবু ও ধনেপাতা মেশাও।",source:"NHLBI · DASH eating plan",url:"https://www.nhlbi.nih.gov/health/dash-eating-plan"},
  {tab:"ফ্যাটি লিভার",title:"পানীয় ও খাবারের পরিমাণে নজর দাও",icon:Leaf,less:"চিনিযুক্ত শরবত ও কোমল পানীয়",more:"পানি বা চিনি ছাড়া লেবুপানি",left:CupSoda,right:GlassWater,why:"চিনিযুক্ত পানীয় থেকে সহজেই অতিরিক্ত চিনি ও ক্যালরি আসে। এগুলো কমানো এবং পরিমিত খাওয়া ফ্যাটি লিভারের খাদ্যাভ্যাসের অংশ।",idea:"দুপুরের শরবতের বদলে পানি রাখো। মিষ্টি কিছু চাইলে পরিমিত আস্ত ফল নাও।",source:"NIDDK · Eating, diet & nutrition",url:"https://www.niddk.nih.gov/health-information/liver-disease/nafld-nash/eating-diet-nutrition"}
] as const;

export function FoodGuide({logMeal}:{logMeal:()=>void}){
  const [group,setGroup]=useState(0),[goal,setGoal]=useState(0);
  const chosen=portions[group],guide=goals[goal];
  return <section className="foodguide" aria-labelledby="foodtitle">
    <div className="foodhead"><div className="title-icon"><Utensils/><h2 id="foodtitle">খাবার বাছাইয়ের গাইড</h2></div><button className="outline" onClick={logMeal}><BookOpen size={17}/>খাবার লিখি</button></div>
    <div className="foodgrid"><div className="platepanel">
      <h3>দুপুর বা রাতের প্লেট</h3><p>একটি ভাগে চাপ দিয়ে দেশি খাবারের উদাহরণ দেখো।</p>
      <div className="plate" role="group" aria-label="খাবারের প্লেটের তিনটি ভাগ">{portions.map((p,i)=><button type="button" key={p.name} className={'portion '+p.color} aria-label={p.name+' '+p.fraction} aria-pressed={group===i} onClick={()=>setGroup(i)}><p.icon size={26}/><b>{p.fraction}</b><span>{p.name}</span></button>)}</div>
      <div className="portiontext" aria-live="polite"><strong>{chosen.name} · {chosen.fraction} প্লেট</strong><p>{chosen.examples} {chosen.reason}</p></div>
      <a className="nutrisource" href="https://professional.diabetes.org/sites/dpro/files/2026-03/030926-oa26-plate-final.pdf" target="_blank" rel="noreferrer">প্লেটের অনুপাত · ADA</a>
    </div><div className="goalpanel"><h3>কোন কারণে কী বেছে নেবে?</h3>
      <div className="goals" role="group" aria-label="খাবার বেছে নেওয়ার কারণ">{goals.map((g,i)=><button key={g.tab} type="button" aria-pressed={i===goal} onClick={()=>setGoal(i)}>{g.tab}</button>)}</div>
      <div className="goalbody" aria-live="polite"><h4>{guide.title}</h4>
      <div className="swap"><div className="less"><guide.left size={23}/><small>কমাও</small><strong>{guide.less}</strong></div><div className="more"><guide.right size={23}/><small>বেছে নাও</small><strong>{guide.more}</strong></div></div>
      <p><b>কেন কাজে দেয়</b> {guide.why}</p><p className="idea"><b>ঘরের উদাহরণ</b> {guide.idea}</p>
      <a className="nutrisource" href={guide.url} target="_blank" rel="noreferrer">তথ্যসূত্র · {guide.source}</a></div>
    </div></div><p className="foodnote">এটি সাধারণ খাবারের উদাহরণ। তোমার চিকিৎসক বিশেষ খাদ্যতালিকা দিলে পরিমাণ ও উপকরণ সে অনুযায়ী বেছে নাও।</p>
  </section>
}
