import { mdiRobot, mdiContentSave } from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useState } from 'react';
import CardBox from '../components/CardBox';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import FormField from '../components/FormField';
import BaseButton from '../components/BaseButton';
import BaseButtons from '../components/BaseButtons';
import { getPageTitle } from '../config';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { aiResponse } from '../stores/openAiSlice';
import axios from 'axios';

const StoryStudio = () => {
  const [idea, setIdea] = useState('');
  const dispatch = useAppDispatch();
  const { aiResponse: aiData, isAskingResponse } = useAppSelector((state) => state.openAi);

  const handleGenerate = () => {
    dispatch(aiResponse({
      input: [
        { role: 'system', content: 'You are an expert Agile Product Owner. Convert raw product ideas into a structured User Story (As a, I want, So that) and provide 3 Acceptance Criteria.' },
        { role: 'user', content: idea },
      ],
      options: { poll_interval: 5, poll_timeout: 300 }
    }));
  };

  const handleSave = async () => {
    // Basic extraction
    const storyText = aiData?.output?.[0]?.content?.[0]?.text || '';
    await axios.post('/user_stories', { 
        title: idea.substring(0, 50),
        asA: 'User',
        iWant: idea,
        soThat: 'Value',
        status: 'Draft'
    });
    alert('Story saved!');
  };

  return (
    <>
      <Head><title>{getPageTitle('Story Studio')}</title></Head>
      <SectionMain>
        <SectionTitleLineWithButton icon={mdiRobot} title="Story Studio" main />
        <CardBox>
          <FormField label="Raw Idea" labelFor="idea">
            <textarea
              id="idea"
              className="w-full p-3 border border-gray-300 rounded"
              rows={4}
              value={idea}
              onChange={(e) => setIdea(e.target.value)}
              placeholder="e.g. Users should be able to reset their passwords..."
            />
          </FormField>
          <BaseButtons>
            <BaseButton color="info" label={isAskingResponse ? 'Generating...' : 'Generate Story'} onClick={handleGenerate} disabled={isAskingResponse} />
          </BaseButtons>
        </CardBox>

        {aiData && (
          <CardBox className="mt-6">
            <h2 className="text-xl font-bold mb-4 text-emerald-600">AI Generated Story</h2>
            <div className="whitespace-pre-wrap">{aiData?.output?.[0]?.content?.[0]?.text}</div>
            <BaseButtons className="mt-4">
              <BaseButton color="success" icon={mdiContentSave} label="Save Story" onClick={handleSave} />
            </BaseButtons>
          </CardBox>
        )}
      </SectionMain>
    </>
  );
};

StoryStudio.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default StoryStudio;
